每当我在C#应用程序中单击表单的提交按钮时,它就会崩溃。该程序假设将所有数据带到在Microsoft SQL Server中制成的我的数据库中下面是代码
string connection = "Data Source=DESKTOP-EON545D;Initial Catalog=TMS_Database;Integrated Security=True";
public LoginFrame()
{
InitializeComponent();
con = new SqlConnection(connection);
}
private void button2_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)//if terms and conditions are accepted
{
AddNewTenant();
}
}
public void AddNewTenant()
{
string username = textBox1.Text.ToString();
string password = textBox2.Text.ToString();
string email = textBox7.Text.ToString();
string firstName = textBox5.Text.ToString();
string lastName = textBox6.Text.ToString();
string address = richTextBox1.Text.ToString();
int phone = int.Parse(textBox8.Text.ToString());
string CNIC = textBox9.Text.ToString();
string appartmentType = radioButton1.Text.ToString();
string sqlStatement = "INSERT INTO tenant(username,password,firstname,lastname,email,current_address,phone,appartmentType)values" + "'" + username + "'," + "'" + password + "'," + "'" + firstName + "'," + "'" + lastName + "'," + "'" + email + "'," + "'" + address + "'," + "'" + phone + "'," + "'" + appartmentType + "')";
//Console.WriteLine(sqlStatement);
SqlCommand cmd = new SqlCommand(sqlStatement, con);
con.Open();
int rowsinsert = cmd.ExecuteNonQuery();
con.Close();
}
您的SQL查询字符串在“值”附近有问题。
string sqlStatement = "INSERT INTO
tenant(username, password, firstname, lastname, email, current_address, phone,
appartmentType) values(" + "'" + username + "'," + "'" + password + "'," + "'" +
firstName + "'," + "'" + lastName + "'," + "'" + email + "'," + "'" + address + "'," +
"'" + phone + "'," + "'" + appartmentType + "')";
您在值后错过了'('。并且我建议使用以下语法
string sqlStatement =“插入到
承租人(用户名,密码,名字,姓氏,电子邮件,当前地址,电话,公寓类型)值(@用户名,@密码,@名字,@姓,@电子邮件,@地址,@电话,@appartmentType)“;
SQLiteCommand command = new SQLiteCommand(con)
command.Text = sqlStatement;
command.CommandType = SQLiteCommandType
command.CommandType = CommandType.Text;
command.Parameters.Add(new SQLiteParameter("@username", username));
command.Parameters.Add(new SQLiteParameter("@password", password));
command.Parameters.Add(new SQLiteParameter("@firstname", firstname));
command.Parameters.Add(new SQLiteParameter("@lastname", lastname));
command.Parameters.Add(new SQLiteParameter("@email", email));
command.Parameters.Add(new SQLiteParameter("@current_address", current_address));
command.Parameters.Add(new SQLiteParameter("@phone", phone));
command.Parameters.Add(new SQLiteParameter("@appartmentType", appartmentType));
command.ExecuteNoneQuery();