开发者

Reading Data From Access Database in C#

Hi want to read data from data base from the given ID (not Premanent). I am using 开发者_Python百科the following code:

        OleDbConnection co = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb");
        co.Open();
        **OleDbCommand cmd = new OleDbCommand("SELECT * FROM Category1 Where ID = '"+textBox1.Text+"'", co);**
        OleDbDataReader reader = cmd.ExecuteReader();

        int i = 1;
        while (reader.Read())
        {
            ListViewItem li = new ListViewItem(i.ToString());
            li.SubItems.Add(reader.GetString(1));
            li.SubItems.Add(reader.GetString(2));
            li.SubItems.Add(reader.GetString(3));
            li.SubItems.Add(reader.GetString(4));
            listView1.Items.Add(li);
            i++;
        }

but it shows me an error message on the Bold line of code:

Data type mismatch in criteria expression.


Is the ID field numeric? You are comparing it to a string. That might be part of the problem.


Like other people said: it sounds very much like ID isn't a string. However you should use parameters when adding user input or any variables to your SQL statement: http://weblogs.sqlteam.com/jeffs/archive/2006/07/21/10728.aspx

OleDbCommand cmd = new OleDbCommand("SELECT * FROM Category1 WHERE id = @id", co);
cmd.Parameters.AddWithValue("@id", textBox1.Text);


Like other people said: it sounds very good working

string strDSN = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\Db1.accdb";
string strSQL = "SELECT * FROM Tbl1" ;
// create Objects of ADOConnection and ADOCommand
OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbDataAdapter myCmd = new OleDbDataAdapter( strSQL, myConn ); 
myConn.Open();
DataSet dtSet = new DataSet();
myCmd.Fill( dtSet, "Tbl1" );
DataTable dTable = dtSet.Tables[0];
foreach( DataRow dtRow in dTable.Rows )
{
    listBox1.Items.Add( dtRow["id"].ToString());
    listBox2.Items.Add( dtRow["nm"].ToString());
    listBox3.Items.Add(dtRow["ag"].ToString());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜