"Select * from Table where Name='WGK' and PASS='111'."; 这条查询语句我知道,我就是不知道当表里面没这个记录的时候怎么返回一个MessageBox.和怎么赋值给 TextBox1.和 TextBox2
首先给你一个方法: /// <summary> /// 访问数据库,从数据库中获取数据表。 /// </summary> /// <param name="selectCommand">参数为查询语句。</param> /// <returns>以数据表的格式返回查询数据。</returns> public DataTable GetData(string selectCommand) { try { // Specify a connection string. string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=StaffRoom.mdb"; connection = new OleDbConnection(connectionString); // Create a new data adapter based on the specified query. oledbda = new OleDbDataAdapter(selectCommand, connection); // Create a command builder to generate SQL update, insert, and // delete commands based on selectCommand. These are used to // update the database. oledbcb = new OleDbCommandBuilder(oledbda); // Populate a new data table and bind it to the BindingSource. DataTable table = new DataTable(); table.Locale = System.Globalization.CultureInfo.InvariantCulture; oledbda.Fill(table); bindingSource1.DataSource = table; return (table); } catch (OleDbException) { MessageBox.Show("数据库连接失败!"); return null; } }然后在程序中这样写: DataTable myTable=new DataTable(); string strSelect="Select * from Table where NAME='WGK' and PASS='111'."; myTable=GetData(strSelect); if(myTable.Rows.Count==0) MessageBox.Show("....."); else { TextBox1.Text=myTable.Rows[0][0].toString(); TextBox2.Text=myTable.Rows[0][1].toString(); }这样应该就行
这条查询语句我知道,我就是不知道当表里面没这个记录的时候怎么返回一个MessageBox.和怎么赋值给 TextBox1.和 TextBox2
/// <summary>
/// 访问数据库,从数据库中获取数据表。
/// </summary>
/// <param name="selectCommand">参数为查询语句。</param>
/// <returns>以数据表的格式返回查询数据。</returns>
public DataTable GetData(string selectCommand)
{
try
{
// Specify a connection string.
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=StaffRoom.mdb"; connection = new OleDbConnection(connectionString); // Create a new data adapter based on the specified query.
oledbda = new OleDbDataAdapter(selectCommand, connection); // Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
oledbcb = new OleDbCommandBuilder(oledbda); // Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
oledbda.Fill(table);
bindingSource1.DataSource = table; return (table);
}
catch (OleDbException)
{
MessageBox.Show("数据库连接失败!");
return null;
}
}然后在程序中这样写:
DataTable myTable=new DataTable();
string strSelect="Select * from Table where NAME='WGK' and PASS='111'.";
myTable=GetData(strSelect);
if(myTable.Rows.Count==0)
MessageBox.Show(".....");
else
{
TextBox1.Text=myTable.Rows[0][0].toString();
TextBox2.Text=myTable.Rows[0][1].toString();
}这样应该就行