C# MySQL 在将数据插入我的表中时遇到致命错误
本文关键字:遇到 致命错误 我的 插入 MySQL 数据 | 更新日期: 2023-09-27 18:33:26
我有一个名为"AddUser"的方法,它应该将数据插入到我的表中,但是每当我执行它时,都会抛出MySqlException。
异常消息:
命令执行期间遇到致命错误。
我的专栏:
Column Type Null Default Comments
Identity Number int(11) No auto_increment
Full Name varchar(32) No
Birthday date No
Sex varchar(6) No
City varchar(32) No
Region varchar(32) No
Zip Code varchar(10) No
Country varchar(32) No
Phone Number varchar(15) No
Email Address varchar(255) No
Ticket Number varchar(8) No
Registration timestamp No CURRENT_TIMESTAMP
我的代码:
private MySqlConnection mySqlConnection;
private async void OpenConnection()
{
if (mySqlConnection == null)
{
mySqlConnection = new MySqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
}
await mySqlConnection.OpenAsync();
}
private async void CloseConnection()
{
if (mySqlConnection != null)
{
await mySqlConnection.CloseAsync();
}
}
private async Task<bool> AddUser(
string fullName,
string birthday,
string sex,
string city,
string region,
string zipCode,
string country,
string phoneNumber,
string emailAddress)
{
try
{
OpenConnection();
MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = string.Format("INSERT INTO Users (Identity_Number, Full_Name, Birthday, Sex, City, Region, Zip_Code, Country, Phone_Number, Email_Address, Ticket_Number, Registration_Time) VALUES (@Identity_Number, @Full_Name, @Birthday, @Sex, @City, @Region, @Zip_Code, @Country, @Phone_Number, @Email_Address, @Ticket_Number, @Registration_Time);");
mySqlCommand.Parameters.Add("@Full_Name", MySqlDbType.VarChar).Value = fullName;
mySqlCommand.Parameters.Add("@Birthday", MySqlDbType.Date).Value = birthday;
mySqlCommand.Parameters.Add("@Sex", MySqlDbType.VarChar).Value = sex;
mySqlCommand.Parameters.Add("@City", MySqlDbType.VarChar).Value = city;
mySqlCommand.Parameters.Add("@Region", MySqlDbType.VarChar).Value = region;
mySqlCommand.Parameters.Add("@Zip_Code", MySqlDbType.VarChar).Value = zipCode;
mySqlCommand.Parameters.Add("@Country", MySqlDbType.VarChar).Value = country;
mySqlCommand.Parameters.Add("@Phone_Number", MySqlDbType.VarChar).Value = phoneNumber;
mySqlCommand.Parameters.Add("@Email_Address", MySqlDbType.VarChar).Value = emailAddress;
mySqlCommand.Parameters.Add("@Ticket_Number", MySqlDbType.VarChar).Value = Guid.NewGuid().ToString().GetHashCode().ToString("X");
await mySqlCommand.ExecuteNonQueryAsync();
CloseConnection();
mySqlCommand.Dispose();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
有人能够检查我的代码并让我知道我做错了什么吗?还有也许我如何改进我的代码?提前谢谢。
谢谢@Plutonix你的回答。我删除了下划线,并按照您的建议转义了包含空格的列名,并带有反引号。代码现在可以工作了。
mySqlCommand.CommandText = string.Format("INSERT INTO Users (`Full Name`, Birthday, Sex, City, Region, `Zip Code`, Country, `Phone Number`, `Email Address`, `Ticket Number`) VALUES (@Full_Name, @Birthday, @Sex, @City, @Region, @Zip_Code, @Country, @Phone_Number, @Email_Address, @Ticket_Number);");