SQL Server数据库连接错误
本文关键字:错误 数据库连接 Server SQL | 更新日期: 2023-09-27 18:03:13
基本上我正在努力开发一个软件,我是新的编程。我试图插入文本框的数据到SQL Server 2008 R2标准,我得到一个错误:
系统。NullReferenceException未处理
这是我的代码。
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
con.Close();
实际上我的数据集是空的,这就是为什么它显示NULL错误
da.Fill(ds, "tbl_studentData");
我用这些行来填充它,现在一切都很好。感谢大家的宝贵时间。
完全按照错误告诉你的去做。用try catch像这样处理它:
try{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
da.Update(ds);
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
DataRow drow = ds.Tables[0].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables[0].Rows.Add(drow);
SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(da);
da.InsertCommand = cmdbuilder.GetInsertCommand();
da.Update(ds);
ds.AcceptChanges();
con.Close();