简体   繁体   English

使用C#将点符号插入到MySQL错误

[英]Insert dot symbol with C# to mySQL error

I'm facing a strange problem, I do an INSERT query to MySQL DB 我面临一个奇怪的问题,我对MySQL数据库执行INSERT查询

                string site = txtSite.Text;
                string query = "INSERT INTO `site`(`id`, `url`, `status`) VALUES (NULL,?url, 1)";

                MySqlCommand cmd = new MySqlCommand(query);
                cmd.Parameters.AddWithValue("?url", site);
                //cmd.Parameters.AddWithValue("?url", "abc.com");
                cmd.Connection = (MySqlConnection)connection;
                cmd.Prepare();

                cmd.ExecuteNonQuery();

1. If I enter "abc.com" into textbox txtSite, and run the code, it said error 1.如果我在文本框txtSite中输入“ abc.com”,然后运行代码,则提示错误

Fatal error encountered during command execution. 命令执行期间遇到致命错误。

  1. But if I don't get value of txtSite, I put "abc.com" to ?url directly, the cmd run OK, not error. 但是,如果我没有获得txtSite的值,则将“ abc.com”直接放在?url上,该cmd运行正常,而不是错误。

Can you have any ideas? 你有什么主意吗?

I believe this is a syntax issue. 我相信这是一个语法问题。 The following code may work for you. 以下代码可能适合您。

string site = txtSite.Text;
string query = "INSERT INTO `site`(`id`, `url`, `status`) VALUES (NULL, @url, 1)";

MySqlClientconn conn = new MySqlConnection();
conn.Open();

MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Prepare();

cmd.Parameters.AddWithValue("@url", site);

cmd.ExecuteNonQuery();

I am assuming you are using the MySQL Connector/Net library. 我假设您正在使用MySQL Connector / Net库。 Don't forget to close the connection and dispose of the command and the connection when you are done. 完成后,不要忘记关闭连接并处理命令和连接。

Reference 参考

For more info on using the MySQL Connector/Net library, see the following: https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html 有关使用MySQL Connector / Net库的更多信息,请参见以下内容: https : //dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html

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

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