使用ASP.net中的参数将数据插入MySqlDatabase(vb.net)

时间:2021-12-05 16:40:52

I'm having some problems when I try to insert data to my database(mysql). It seems my connection isn't working, but I doubt it because I can retrieve data from it yet no luck on inserting. I've also tried various things and I still can't come up with a solution nor find the cause of error.

当我尝试将数据插入数据库(mysql)时,我遇到了一些问题。似乎我的连接不起作用,但我怀疑它,因为我可以从中检索数据,但插入时没有运气。我也尝试了各种各样的东西,我仍然无法找到解决方案,也找不到错误的原因。

Can somebody help me out? Your concern is very much appreciated!

有人可以帮帮我吗?非常感谢您的关注!

Here's my Registration.aspx page

Imports MySql.Data.MySqlClient
Imports System.Web.Security
Imports System.Security.Cryptography
Imports System.Web.Configuration
Imports System.Configuration
Partial Class Register
    Inherits System.Web.UI.Page
    Dim ctc As New Class1
    Dim conn As MySqlConnection
    Dim connstr As String = ConfigurationManager.ConnectionStrings("dbconn").ConnectionString
    Dim cmd As MySqlCommand
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Try
            conn = New MySqlConnection(connstr)
            conn.Open()

            cmd = New MySqlCommand("INSERT INTO tbl_uinfo (user_id, fname, lname, email, pword, paypal) values (null,@fname,@lname,@email,@pword,@paypal)")
            cmd.Parameters.Add("@fname", MySqlDbType.VarChar, 45).Value = firstname.Text
            cmd.Parameters.Add("@lname", MySqlDbType.VarChar, 45).Value = lastname.Text
            cmd.Parameters.Add("@email", MySqlDbType.VarChar, 45).Value = email.Text
            cmd.Parameters.Add("@pword", MySqlDbType.VarChar, 250).Value = password2.Text
            cmd.Parameters.Add("@paypal", MySqlDbType.VarChar, 45).Value = paypal.Text

            cmd.ExecuteNonQuery()



            conn.Dispose()
            conn.Close()
            cmd.Dispose()
        Catch ex As Exception
            MsgBox("Registration failed." & ex.Message)
        End Try

    End Sub
End Class

Here's my ConnectionString (web.config)

<connectionStrings>
        <add name="dbconn" connectionString="server=localhost;database=db_aspweb;user id=root; pwd=root"/>
    </connectionStrings>

My Database

CREATE TABLE `tbl_uinfo` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(45) DEFAULT NULL,
  `lname` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `pword` varchar(250) DEFAULT NULL,
  `paypal` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `paypal` (`paypal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The error I am getting so far

"Registration Failed. Connection must be valid and open."

“注册失败。连接必须有效且开放。”

1 个解决方案

#1


0  

Pass the connection (connstr) to the command object (cmd) either by constructor or property.

通过构造函数或属性将连接(connstr)传递给命令对象(cmd)。

#1


0  

Pass the connection (connstr) to the command object (cmd) either by constructor or property.

通过构造函数或属性将连接(connstr)传递给命令对象(cmd)。