我创建了与 Microsoft sql 数据库的连接,并尝试添加基本信息作为练习的一部分,但出现以下错误。
Object reference not set to an instance of an object
这就是我连接到数据库的方式
SqlConnection sqlConn;
protected void butConnect_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=lrmg;Integrated Security=True;";
sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
labMessage.Text = "a connection to your database was established";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
这是我得到错误的地方
protected void butSubmit_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string date = txtDate.Text;
**SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES('" + name + "'," + date + ")";
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
}
我的印象是sql连接已打开,为什么会出现异常?