繁体   English   中英

尝试在DataGrid上显示表时出现MySQL错误

[英]MySQL Error While Trying To Display A Table On a DataGrid

这是我正在使用的代码:

private void btn_search_Click(object sender, EventArgs e)
{
    try
    {
        MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=dp;User Id=root;password=''");
        con.Open();
        DataTable dt = new DataTable();
        MySqlDataAdapter SDA = new MySqlDataAdapter("SELECT * FROM dp WHERE id LIKE " + txt_id.Text, con);
        SDA.Fill(dt);
        dataGridView1.DataSource = dt;
    }
    catch (MySqlException ex)
    {
        Console.WriteLine("StackTrace:" + ex.StackTrace);
    }

问题是,它抛出一个MySQL异常,

引发异常:MySql.Data.dll StackTrace中的'MySql.Data.MySqlClient.MySqlException':MySql.Data.MySqlClient.NativeDriver.GetResult(Int32&受影响的行,Int64&insertId)的MySql.Data.MySqlClient.MySqlStream.ReadPacket() MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId,Int32&受影响的行,Int64&insertId)位于MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId,Boolean force)位于MySql.Data.MySqlClient.MySqlDataReader.NextResult() System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior行为)处的MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior行为) .Common.DbDataAdapter.FillInternal(DataSet数据集,DataTable []数据表,Int32 startRecord,Int32 maxRecords,字符串srcTable,IDbCommand命令,CommandBehavior行为)位于System.Data.Common.DbDataAdapter.Fill(DataTable [] dataTables,Int32 startRecord,Int32 maxRecords,IDbCommand命令,CommandBehavior行为)位于C:\\ Users \\ Owner \\ documents \\ visual studio 2015 \\ Projects中Dispatching_Software.SearchUsers.btn_search_Click(Object sender,EventArgs e)处的System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) \\ Dispatching Software \\ Dispatching Software \\ SearchUsers.cs:第34行

我想要做的是在表中搜索用户并显示他们,问题似乎出在SDA.Fill(dt)

您不需要使用con.Open(); 当您使用MySqlDataAdapter 另外,您应该始终使用参数化查询来避免SQL注入

MySqlDataAdapter SDA = new MySqlDataAdapter("SELECT * FROM dp WHERE id LIKE '%' + @a + '%'", con);
SDA.SelectCommand.Parameters.AddWithValue("@a", txt_id.Text);

尽管直接指定类型并使用Value属性比AddWithValue更好:

 MySqlDataAdapter SDA = new MySqlDataAdapter("SELECT * FROM dp WHERE id LIKE @a", con);
SDA.SelectCommand.Parameters.Add("@a", MySqlDbType.VarChar, 200).Value = "%" + txt_id.Text;

我们可以停止使用AddWithValue()吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM