简体   繁体   English

带有MySQL INSERT参数的C#

[英]C# with MySQL INSERT parameters

Good day to all, I'm using Visual C# 2010 and MySQL Version 5.1.48-community. 祝大家好,我正在使用Visual C#2010和MySQL版本5.1.48社区。 I hope you can help me with this code. 我希望你能帮我解决这个问题。 I don't find it working on me. 我觉得它不适合我。 What am I missing? 我错过了什么?

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.Add("@person", "Myname");
comm.Parameters.Add("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

And when I try to compile it. 当我尝试编译它时。 It says: 它说:

Person column cannot be null Person列不能为null

EDITED: 编辑:

But when I try this code. 但是,当我尝试这个代码。

comm.CommandText = "INSERT INTO room(person,address) VALUES('Myname', 'Myaddress')";

But this code is prone to sql injection attack but it works, doesn't gives me an error. 但是这段代码很容易受到sql注入攻击,但它有效,不会给我一个错误。

EDITED: 编辑:

I tried to use this. 我试着用这个。 I found it here so I thought It would work but gives me this error 我发现它在这里,所以我认为它会工作,但给了我这个错误

Index (zero based) must be greater than or equal to zero and less than the size of the argument list. 索引(从零开始)必须大于或等于零且小于参数列表的大小。

Any idea? 任何想法?

    string a = "myname";
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "INSERT INTO room(person,address) VALUES(?,?)";
    //cmd.Prepare();

    cmd.Parameters.Add("person", MySqlDbType.VarChar).Value = a;
    cmd.Parameters.Add("address", MySqlDbType.VarChar).Value = "myaddress";
    cmd.ExecuteNonQuery(); // HERE I GOT AN EXCEPTION IN THIS LINE

Any help would be much appreciated. 任何帮助将非常感激。

EDITED: SOLVED I used this code: 编辑:已解决我使用此代码:

cmd.CommandText = "INSERT INTO room(person,address) VALUES(?person,?address)";
cmd.Parameters.Add("?person", MySqlDbType.VarChar).Value = "myname";
cmd.Parameters.Add("?address", MySqlDbType.VarChar).Value = "myaddress";
cmd.ExecuteNonQuery();

Thanks SO! 谢谢!

You may use AddWithValue method like: 您可以使用AddWithValue方法,如:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

OR 要么

Try with ? 尝试用? instead of @ , like: 而不是@ ,如:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(?person, ?address)";
comm.Parameters.Add("?person", "Myname");
comm.Parameters.Add("?address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

Hope it helps... 希望能帮助到你...

Use the AddWithValue method: 使用AddWithValue方法:

comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");

I had the same issue -- Finally tried the ? 我有同样的问题 - 最后尝试了吗? sigil instead of @, and it worked. sigil而不是@,它起作用了。

According to the docs: 根据文件:

Note. 注意。 Prior versions of the provider used the '@' symbol to mark parameters in SQL. 提供程序的早期版本使用“@”符号标记SQL中的参数。 This is incompatible with MySQL user variables, so the provider now uses the '?' 这与MySQL用户变量不兼容,因此提供程序现在使用'?' symbol to locate parameters in SQL. 用于在SQL中查找参数的符号。 To support older code, you can set 'old syntax=yes' on your connection string. 要支持旧代码,可以在连接字符串上设置“old syntax = yes”。 If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL. 如果您这样做,请注意,如果您未能定义要在SQL中使用的参数,则不会抛出异常。

Really? 真? Why don't you just throw an exception if someone tries to use the so called old syntax? 如果有人试图使用所谓的旧语法,为什么不抛出异常呢? A few hours down the drain for a 20 line program... 几个小时的耗水量为20线计划......

MySQL::MySQLCommand MySQL的::的MySqlCommand

Three things: use the using statement, use AddWithValue and prefix parameters with ? 三件事:使用using语句,使用AddWithValue和前缀参数? and add Allow User Variables=True to the connection string. 并将Allow User Variables=True添加到连接字符串。

 string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
 using (var conn = new MySqlConnection(connString))
 {
      conn.Open();
      var comm = conn.CreateCommand();
      comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
      comm.Parameters.AddWithValue("?person", "Myname");
      comm.Parameters.AddWithValue("?address", "Myaddress");
      comm.ExecuteNonQuery();
  }

Also see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx for more information about the command usage, and http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html for information about the Allow User Variables option ( only supported in version 5.2.2 and above ). 另请参阅http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx以获取有关命令用法的更多信息,以及http://dev.mysql.com/doc/ refman / 5.1 / en / connector-net-connection-options.html以获取有关“允许用户变量”选项的信息( 仅在5.2.2及更高版本中受支持 )。

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. 尝试使用Windows Form Application中的mysql-connector-net-5.1.7-noinstall和Visual Studio(2015)插入数据时,我遇到了类似的问题。 I am not a C# guru. 我不是C#大师。 So, it takes around 2 hours to resolve everything. 因此,解决所有问题大约需要2个小时。

The following code works lately: 以下代码最近起作用:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}
comm.Parameters.Add("person", "Myname");

What I did is like this. 我做的是这样的。

String person;
String address;
person = your value;
address =your value;
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connString);
    conn.Open();
    MySqlCommand comm = conn.CreateCommand();
    comm.CommandText = "INSERT INTO room(person,address) VALUES('"+person+"','"+address+"')";
    comm.ExecuteNonQuery();
    conn.Close();

Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code: 如有必要,请尝试调整“SqlDbType”中的代码以匹配您的数据库类型,并使用以下代码:

comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;

or: 要么:

comm.Parameters.AddWithValue("@person", Myname);

That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype. 这应该工作,但记住使用Command.Parameters.Add(),您可以定义特定的SqlDbType并使用Command.Parameters.AddWithValue(),它将尝试隐式地获取基于参数值的SqlDbType,如果它不能隐式地有时会破坏转换数据类型。

Hope this helps. 希望这可以帮助。

try this it is working 试试这个它是有效的

 MySqlCommand dbcmd = _conn.CreateCommand();
    dbcmd.CommandText = sqlCommandString;
    dbcmd.ExecuteNonQuery();
    long imageId = dbcmd.LastInsertedId;

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

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