gpt4 book ai didi

C# - INSERT 到 DB 的 MySQL 语法错误

转载 作者:行者123 更新时间:2023-11-29 00:26:14 26 4
gpt4 key购买 nike

我在我的程序中遇到 MySqlException 错误。这是一个简单的测试程序,我试图将带有时间戳的日志错误插入到我的数据库中的表中。

//--------------程序------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;


string Log = "Sample Log Error";
string key = "11111";

string date;
string time;
int unixT;
TimeSpan unix_time;

// geting current date in yyyy-mm-dd format
date = DateTime.UtcNow.ToString("yyyy-MM-dd");

//getting current time in hh:mm:ss format
time = string.Format("{0:HH:mm:ss tt}", DateTime.Now);

// Getting Unix Time
unix_time = (System.DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));

//converting Unix time to seconds
unixT = Convert.ToInt32(unix_time.TotalSeconds);

MySqlConnection myConn = new MySqlConnection("Server=172.178.2.143;" + "Port=3306;" + "Database=DB;" + "Uid=user;" + "Pwd=pass;");

try
{
myConn.Open();
}
catch (MySqlException e)
{
Console.WriteLine(e);
}

MySqlCommand comm1 = new MySqlCommand("INSERT INTO Logger(date_stamp, time_stamp, log, unix_time, key) VALUES(@date_stamp, @time_stamp, @log, @unix_time, @key)", myConnection);

//inserting each element from GPS split message into its respective table and column in the database
comm1.Parameters.AddWithValue("date_stamp", date);
comm1.Parameters.AddWithValue("time_stamp", time);
comm1.Parameters.AddWithValue("log", Log);
comm1.Parameters.AddWithValue("unix_time", unixT);
comm1.Parameters.AddWithValue("key", key);

try
{
comm1.ExecuteNonQuery(); //executing the INSERT Query Above
}

catch (MySqlException e)
{
Console.WriteLine(e);
}

myConnection.Close();

//------------结束程序----------------

我收到以下错误:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES('2013-09-13', '16:21:15 PM', 'Sample Log Error', 1379103676, '11111'' at line 1"

最佳答案

KEY 这个词是一个 reserved keyword对于 MySql

如果您想在代码中使用该名称,则需要在其周围添加反引号

 MySqlCommand comm1 = new MySqlCommand("INSERT INTO Logger(date_stamp," + 
"time_stamp, log, unix_time, `key`) " +
"VALUES(@date_stamp, @time_stamp, @log, @unix_time, @key)",
myConnection);

如果在您的应用程序开发阶段还不算太晚,我建议您更改该名称,因为每次您接触该字段时,您都会遇到同样的问题需要记住。

我还想建议 using statement围绕您的代码,只需一次尝试即可

try
{
using(MySqlConnection myConn = new MySqlConnection(.....))
using(MySqlCommand comm1 = new MySqlCommand(......))
{
myConn.Open();
comm1.Parameters.AddWithValue("date_stamp", date);
.....
comm1.ExecuteNonQuery();
}
}
catch (MySqlException e)
{
Console.WriteLine(e);
}

通过这种方式,您可以正确处理边缘情况(无法打开连接,无法执行命令),并且当代码流出右大括号时,您的连接将被正确关闭和处理。

关于C# - INSERT 到 DB 的 MySQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18794816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com