try
{
//insert data into database
//check if data already exists
using (SqlConnection con = new SqlConnection(@"Server=DESKTOP-31579CJ\SQLEXPRESS;Database=LoginInformation;Trusted_connection = True;"))
{
SqlCommand cmd = new SqlCommand(@"SELECT User.Username FROM User WHERE Username = '" Username.Text "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Username already exists");
}
else
{
MessageBox.Show("Account created");
cmd = new SqlCommand(@"INSERT INTO User (Username,Password) VALUES ('" Username.Text "','" Password.Password "')", con);
cmd.ExecuteNonQuery();
//clear textboxes
Username.Text = "";
Password.Password = "";
}
dr.Close();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Exception occured" ": " ex.Message);
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-31579CJ\SQLEXPRESS;Initial Catalog=LoginInformation;Integrated Security=True;User ID = yes; Password = yes");
//create table if one does not exist
SqlCommand cmd = new SqlCommand("CREATE TABLE User (Username varchar(50), Password varchar(50))", con);
}
當我嘗試執行此查詢時,遇到了例外:
關鍵字“用戶”附近的語法不正確
但我并沒有真正經常使用 C# 或 SQL,所以老實說我看不出問題——對此代碼的任何反饋也將不勝感激
uj5u.com熱心網友回復:
我沒有檢查確認,但我猜“用戶”是 T-SQL 中的保留字,所以你需要轉義它:
SqlCommand cmd = new SqlCommand(@"SELECT Username FROM [User] WHERE Username = '" Username.Text "'", con);
請注意,我已從列名中洗掉了表限定符。您可以包含它,但它在涉及單個表的陳述句中毫無意義。如果你確實包含它,你也需要逃避它。
您也必須在其他 SQL 中執行相同的操作。“密碼”也可能是保留字 - 它在 Access 中,但我不確定 SQL Server。
這超出了這個問題的范圍,但你真的不應該使用字串連接將值插入到 SQL 中。這是一種非常糟糕的做法,可能會導致各種問題,包括惡意用戶可能會破壞或洗掉您的整個資料庫。立即了解如何使用引數。這是我對這個問題的看法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/515406.html
標籤:C#。网sql服务器调试
