读书人

关于Access语句更新数据库的有关问题

发布时间: 2012-03-17 19:06:28 作者: rapoo

关于Access语句更新数据库的问题
各位大神,急求解决该问题,我用ACCESS语句写的程序不能够正常运行,却找不出问题,调试时候运行到红色标记的 da.Fill(ds);时就自动跳出try...catch语句,求解原因
[code=C#][/code] private void button4_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
MessageBox.Show("请选择或输入要删除的船只编号信息", "信息提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
else
{
DataSet ds = new DataSet();
string strFilePath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\DB_Test.mdb";
// 判断要删除的数据信息是否存在
string sql = string.Format("SELECT * FROM 抛石信息 where 船只编号='{0}'", textBox1.Text.Trim() );
//定义SQL Server连接对象
System.Data.OleDb.OleDbConnection con = new OleDbConnection(strFilePath);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
da.Fill(ds); if (ds.Tables[0].Rows.Count > 0)
{
if (MessageBox.Show("确认要删除该抛石信息吗?", "信息提示", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
//定义删除数据信息的SQL语句
sql = string.Format(@"delete 抛石信息 from 抛石信息 where 船只编号='{0}'", textBox1.Text.Trim());
//定义SQL Server连接对象
System.Data.OleDb.OleDbConnection cons = new OleDbConnection(strFilePath);
System.Data.OleDb.OleDbCommand cmd = new OleDbCommand(sql, cons);
try
{
cons.Open();
cmd.ExecuteNonQuery();

}
catch { }
finally
{
cons.Close();
cons.Dispose();
cmd.Dispose();
}
MessageBox.Show("信息删除成功", "信息提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
//刷新数据
string sqls = "select * from 抛石信息 order by 船只编号";
System.Data.OleDb.OleDbDataAdapter da1 = new OleDbDataAdapter(sqls, con);
DataSet dss = new DataSet();
da1.Fill(dss);
if (dss.Tables[0].Rows.Count > 0)
{
dataGridView1.DataSource = dss.Tables[0];
}
}
}
}
}
catch { }
}

[解决办法]
SQL语句的问题,断点跟踪一下,很快就能发现错误的。

sql = string.Format(@"delete 抛石信息 from 抛石信息 where 船只编号='{0}'", textBox1.Text.Trim()); //红色多余

==============》改成

sql = string.Format("delete from 抛石信息 where 船只编号='{0}'", textBox1.Text.Trim());



还有就是那个船只编号是字符型的嘛?是的话,这样写是正确的,如果是数字的话,

sql = string.Format("delete from 抛石信息 where 船只编号={0}", int.Parse(textBox1.Text.Trim()));
[解决办法]
这是因为ds.Tables.count就是0,你ds里面就没有东西啊,最好加个判断吧,判断是否找到了表,网上类似这样的问题很多,你的catch里应该是“无法找到表 0”的错误提醒,自己找找吧~

读书人网 >C#

热点推荐