我使用SQL Server数据库作为后端创建了一个ASP.Net项目。我显示以下错误。怎么解决这个问题?
===============编码
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra As Integer
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
myConnection = New SqlConnection("Data Source=JANANI-FF079747\SQLEXPRESS;Initial Catalog=new;Persist Security Info=True;User ID=sa;Password=janani") 'server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Insert into table3 values 'janani','jan'")
ra = myCommand.ExecuteNonQuery() ========---> error is showing here
MsgBox("New Row Inserted" & ra)
myConnection.Close()
End Sub
End Class
=========错误讯息============
ExecuteNonQuery: Connection property has not been initialized.
答案 0 :(得分:3)
创建SqlCommand
时,需要将其与连接关联:
myCommand =
New SqlCommand("Insert into table3 values 'janani','jan'", myConnection);
答案 1 :(得分:1)
试试这个,下面的代码正确地处理了所有非托管资源,并且连接已正确初始化:
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = dataConnection.CreateCommand())
{
dataCommand.CommandText = "Insert into table3 values 'janani','jan'"
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
答案 2 :(得分:0)
myCommand = New SqlCommand("Insert into table3 values 'janani','jan'", myConnection)