插入错误C#,访问 [英] Insert Into error c#, access
本文介绍了插入错误C#,访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图插入一条记录以访问数据库,但是在insert into语句中不断出现语法错误.
I am trying to insert a record to access database but keeps getting syntax error in insert into statement.
请帮助我.
try
{
cnn.Open();
OleDbCommand savea = new OleDbCommand();
savea.Connection = cnn;
savea.CommandText = "INSERT INTO FirstYear(LastName, FirstName, MiddleName, ContactNumber, Age, BirthDateYear, HomeAddress, Gender, Religion, Citizenship, GuardianName, GuardianContactNum, RelationtoStudent, Work, GuardianHomeAddress) values ('" + lastname.Text + "' , '" + firstname.Text + "' , '" + middlename.Text + "' , " + contactnum.Text + " , " + age.Text + " , '" + dateTimePicker1.Text + "' , '" + homeadd.Text + "' , '" + gender.Text + "' , '" + religion.Text + "', '" + citizenship.Text + "' , '" + fullname.Text + "' , " + gcontactnum.Text + " , '" + rrelation.Text + "' , '" + work.Text + "' , '" + ghomeadd.Text + "')";
int temp = savea.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("Successfully Submitted");
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
cnn.Close();
推荐答案
您有很多''
不匹配的地方.另外,当前您的代码容易受到Sql Injection的攻击,请始终使用参数.还要使用using
块以确保对象已关闭并正确放置
You've got a a fair few ''
mismatches . Also currently your code is vulnerable to Sql Injection, always use parameters. Also make use of using
block to ensure the object is closed and disposed correctly
string myQuery = "INSERT INTO FirstYear(LastName, FirstName, ...) values (@Lastname, @Firstname, ... )";
using (var cmd = new OleDbCommand(myQuery, connectionString))
{
cmd.Parameters.Add("@Lastname", OleDbType.VarChar).Value = lastname.Text;
cmd.Parameters.Add("@Firstname", OleDbType.VarChar).Value = firstname.Text;
...
}
这篇关于插入错误C#,访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文