[英]connection error between sql and C#
我已經在我的sql服務器上創建了該表:
create table Empolyee(
ESSN int not null,
EFirstName varchar(20) not null ,
ELastName varchar(20) not null,
EJob varchar(20),
EBDate date,
ESalary int,
primary key(ESSN));
在C#中,我嘗試使用該代碼向數據庫添加數據:
SqlConnection sqc = new SqlConnection("Data Source=.\\;Initial Catalog=DB;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("INSERT INTO Empolyee VALUES (@ESSN,@EFirstName,@ELastName,@EJob,@EBDate,@ESalary)", sqc);
da.SelectCommand.Parameters.Add("@ESSN", SqlDbType.Int).Value = textBox1.Text;
da.SelectCommand.Parameters.Add("@EFirstName", SqlDbType.VarChar).Value = textBox2.Text;
da.SelectCommand.Parameters.Add("@ELastName", SqlDbType.VarChar).Value = textBox3.Text;
da.SelectCommand.Parameters.Add("@EJob", SqlDbType.VarChar).Value = textBox4.Text;
da.SelectCommand.Parameters.Add("@EBDate", SqlDbType.Date).Value = maskedTextBox1.Text;
da.SelectCommand.Parameters.Add("@ESalary", SqlDbType.Int).Value = textBox5.Text;
// open connection
sqc.Open();
// excute the command
da.InsertCommand.ExecuteNonQuery();
// close connection
sqc.Close();
我在運行時收到該錯誤:對象引用未設置為對象的實例或System.NullReferenceException:對象引用未設置為對象的實例。
您沒有為da.InsertCommand
分配任何da.InsertCommand
-而是將INSERT
命令放入da.SelectCommand
...,只需將問題中顯示的代碼中所有引用從da.SelectCommand
更改為da.InsertCommand
:
da.InsertCommand = new SqlCommand("INSERT INTO Empolyee VALUES (@ESSN,@EFirstName,@ELastName,@EJob,@EBDate,@ESalary)", sqc);
da.InsertCommand.Parameters.Add("@ESSN", SqlDbType.Int).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("@EFirstName", SqlDbType.VarChar).Value = textBox2.Text;
da.InsertCommand.Parameters.Add("@ELastName", SqlDbType.VarChar).Value = textBox3.Text;
da.InsertCommand.Parameters.Add("@EJob", SqlDbType.VarChar).Value = textBox4.Text;
da.InsertCommand.Parameters.Add("@EBDate", SqlDbType.Date).Value = maskedTextBox1.Text;
da.InsertCommand.Parameters.Add("@ESalary", SqlDbType.Int).Value = textBox5.Text;
順便說一句,你不需要任何SqlDataAdapter
或DataSet
執行一個INSERT
-這是可以做到SqlConnection
和SqlCommand
唯一。
您正在執行以下行:
da.InsertCommand.ExecuteNonQuery()
但是你是init SelectCommand
嘗試替換以下代碼:
da.InsertCommand= new SqlCommand("INSERT INTO Empolyee VALUES (@ESSN,@EFirstName,@ELastName,@EJob,@EBDate,@ESalary)", sqc);
da.InsertCommand.Parameters.Add("@ESSN", SqlDbType.Int).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("@EFirstName", SqlDbType.VarChar).Value = textBox2.Text;
da.InsertCommand.Parameters.Add("@ELastName", SqlDbType.VarChar).Value = textBox3.Text;
da.InsertCommand.Parameters.Add("@EJob", SqlDbType.VarChar).Value = textBox4.Text;
da.InsertCommand.Parameters.Add("@EBDate", SqlDbType.Date).Value = maskedTextBox1.Text;
da.InsertCommand.Parameters.Add("@ESalary", SqlDbType.Int).Value = textBox5.Text;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.