private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// modify the connection string and include any additional required properties for your database
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:\Users\Dastgeer\Documents\Visual Studio 2013\Projects\UrduStemmerProject\UrduStemmerProject\Resources\ProjectDatbase.mdb";
try
{
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(@"SELECT PreFix FROM UrduStemmerTbl WHERE (word = '"+InputWord+"')");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
System.Data.OleDb.OleDbCommand cmd2 = new System.Data.OleDb.OleDbCommand(@"SELECT Stem FROM UrduStemmerTbl WHERE (word = '" + InputWord + "')");
cmd2.Connection = conn;
cmd.ExecuteNonQuery();
System.Data.OleDb.OleDbCommand cmd3 = new System.Data.OleDb.OleDbCommand(@"SELECT PostFix FROM UrduStemmerTbl WHERE (word = '" + InputWord + "')");
cmd3.Connection = conn;
cmd.ExecuteNonQuery();
//Text boxes names are
//prefixOutput.Text =;
//stemOutput.Text = ;
//postfixOutput.Text = ;
MessageBox.Show("Data Stemmed!");
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
答案 0 :(得分:1)
您无需使用ExecuteNonQuery
作为SELECT
语句。此方法只执行您的查询,它不会返回任何数据或其他内容。
您的查询看起来只返回一行一行,您可以使用ExecuteScalar
方法。
但更重要的是,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
还可以使用using
statement自动处理您的连接和命令,而不是手动调用Close
方法。
顺便说一句,您可以将所有OleDbCommand
个对象合并为一个,因为您在同一个表中查询不同的列。
using(var conn = new OleDbConnection(connString))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT PreFix, Stem, PostFix FROM UrduStemmerTbl WHERE word = ?";
cmd.Parameters.Add("?", OleDbType.VarWChar).Value = InputWord;
// I assume your column type
conn.Open();
using(var dr = cmd.ExecuteReader())
{
if(dr.Read())
{
prefixOutput.Text = dr.GetString(0);
stemOutput.Text = dr.GetString(1);
postfixOutput.Text = dr.GetString(2);
}
}
}