1、同事定義了1個資料庫,資料庫內有1個欄位命名為long,和C#的保留字重名
2、我在畫面上定義1個textBox4控制元件,和1個button按鈕,希望點一下按鈕,往資料插入一次textBox4控制元件的數值。
int mlong = Convert.ToInt32(TextBox4.Text);
string ConnectionStr = "server=localhost;port=3306;user Id=root;password=12345678; database=cableid ;Allow User Variables=True";
MySqlConnection Connection = new MySqlConnection(ConnectionStr);
MySqlCommand command = new MySqlCommand();
command.Connection = Connection;
try
{
Connection.Open();
MySqlCommand cmd = new MySqlCommand("insert into table1 set mlong=@long, ", Connection);
cmd.Parameters.AddWithValue("@long", mlong);
if (cmd.ExecuteNonQuery() > 0)
{
Response.Write("<script>alert('添加成功')</script>");
}
else
{
Response.Write("<script>alert('添加失敗')</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert(ex.Message)</script>");
}
現在存在的問題是: 插不進資料庫中,沒有任何回應。
uj5u.com熱心網友回復:
一、定義的欄位名為long,該欄位名和C#的保留字long重名,用如下方法int mlong = Convert.ToInt32(TextBox4.Text);
MySqlCommand cmd = new MySqlCommand("insert into table1 set mlong=@long, ", Connection);
cmd.Parameters.AddWithValue("@long", mlong);
cmd.ExecuteNonQuery() ;
無法將mlong插入到資料庫中。
二、但是只要將資料庫中的欄位名修改為mlong,用如下方法
int mlong = Convert.ToInt32(TextBox4.Text);
MySqlCommand cmd = new MySqlCommand("insert into table1 set mlong=@mlong, ", Connection);
cmd.Parameters.AddWithValue("@mlong", mlong);
cmd.ExecuteNonQuery() ;[/code]
就可以將mlong插入到資料庫中。
uj5u.com熱心網友回復:
關鍵字重名,可以加at符號uj5u.com熱心網友回復:
欄位名沒有和MySQL的關鍵字重名,而是和C#的關鍵字重名呀!
uj5u.com熱心網友回復:
public async Task<ExecutionResult> insertRecord(string strDBName, string strTableName, string strInsertRecord)//增
{
ExecutionResult er = new ExecutionResult();
return await Task<ExecutionResult>.Run(() =>
{
try
{
string strSelectDB = $"USE {strDBName}";
MySqlCommand cmdSelectDB = new MySqlCommand(strSelectDB, conn);
conn.Open();
cmdSelectDB.ExecuteNonQuery();
MySqlCommand cmd = new MySqlCommand(strInsertRecord, conn);
cmd.ExecuteNonQuery();
conn.Close();
er.Status = true;
er.Message = $"insert {strDBName}->{strTableName} successfully";
}
catch (Exception e)
{
er.Status = false;
er.Message = $"insert {strDBName}->{strTableName} fail: {e.ToString()}";
}
return er;
});//添加一條記錄
}
uj5u.com熱心網友回復:
private MySqlConnection conn = new MySqlConnection("Data Source=localhost;Persist Security Info=yes;UserId=root; PWD=Password");
https://blog.csdn.net/ericwuhk/article/details/106411528
uj5u.com熱心網友回復:
欄位名用''刮起來不就行了。 比如'long'或者`long`轉載請註明出處,本文鏈接:https://www.uj5u.com/net/165493.html
標籤:C#
