我在c#中工作并将我的数据插入Access数据库。它运行正常但在我尝试插入数据时崩溃,任何想法为什么?
public partial class StudentInfo : Form
{
private OleDbConnection myCon;
public StudentInfo()
{
InitializeComponent();
myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\database program\database program\Students.mdb");
}
private void InsertBtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values ('"+ Rollnotb.Text+"','"+nametb.Text+"','"+fathertb.Text+"','"+adresstb.Text+"')";
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
答案 0 :(得分:3)
问题可能是您将所有字段作为text
值插入,并且某些字段在MS Access表中被定义为数字(rollNo
?)
此外,习惯在查询中使用参数:
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values (?,?,?,?)";
cmd.Parameters.Add(new OleDbParameter("@rollNo", rollNoValue)); //etc.