C# 与 SQL Server 2008 的连接

C# connectivity with SQL Server 2008

当我想连接到 SQL Server 2008 数据库时遇到此错误。

错误:

System.InvalidOperationException: ExecuteNonQuery: Connection property, has not been initialized.
at System.Data.Sq1Client.Sq1Command.ValidateCommand(String method, Boolean async)
at System.Data.Sq1Client.Sq1CommandinternalExecuteNonQuery(TaskCompletionS ource'1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.Sq1Client.Sq1Command.ExecuteNonQuery()
at WindowsFormsApplication2.Form1.create_Click(Object sender, EventArgs e) in C:\Users\admin\Documents\Visual Studio 201CAProjects\WindowsFormsApplicationaWindowsFormsApplicationaForm1.cs line 127

SqlCommand cmd = new SqlCommand(); 
cmd.CommandText="insert into dbo.Student_Record
                  (
                    ID,
                    Name,
                    [Father's CNIC], 
                    [Father's Name],
                    CNIC
                  ) 
                  values 
                 ('BCSF11A003',
                  'Zargham Nazeer Malik',
                  '35202-2953923-3',
                  'Khalid Nazeer Malik',
                  '35202-2235390-5')"; 
cmd.ExecuteNonQuery(); 
con.Close(); 
}

该错误仅表示您在向其分配连接之前尝试使用 SqlCommand

请检查。如果您将代码部分包含在这里,那么它将更有用。

您没有向您的命令添加连接:

cmd.Connection = con;

这段代码应该可以解决您的问题:

using(SqlConnection con = new SqlConnection("CHANGE_THIS_TO_YOUR_CONNECTIONSTRING")){
SqlCommand cmd = con.CreateCommand(); 
cmd.CommandText="insert into dbo.Student_Record(ID,Name,[Father's CNIC],[Father's Name],CNIC) values ('BCSF11A003','Zargham Nazeer Malik','35202-2953923-3','Khalid Nazeer Malik','35202-2235390-5')"; 
cmd.ExecuteNonQuery();  

} 

您必须将 CHANGE_THIS_TO_YOUR_CONNECTIONSTRING 更改为连接字符串。 请参阅:https://www.connectionstrings.com/sql-server/ 了解如何找出正确的字符串。

我这样做是为了包括所有常见的最佳实践:

// define the query - you should use **parameters** to avoid SQL injection
string query = "insert into dbo.Student_Record(ID, Name, [Father's CNIC], [Father's Name], CNIC) values ('BCSF11A003', 'Zargham Nazeer Malik', '35202-2953923-3', 'Khalid Nazeer Malik', '35202-2235390-5');";

// define connection string - typically read from config
string connectionString = "";

// create connection and command objects, set the "conn" connection on the "cmd" object in the constructor
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
    // open connection, execute command, close connection
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}