string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
String uname, pass;
uname = textBox1.Text;
pass = textBox2.Text;
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
String query = "insert into LOGIN_TABLE (UserName, Password) VALUES ('" +
textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "') ";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
OleDbParameter myParm = myCommand.Parameters.Add("@uname", OleDbType.VarChar, 50);
myParm.Value = textBox1.Text;
myParm = myCommand.Parameters.Add("@pass", OleDbType.VarChar, 50);
myParm.Value = textBox2.Text;
myCommand.ExecuteNonQuery();
myConnection.Close();
答案 0 :(得分:3)
您尚未告知OleDbCommand
要使用哪个数据库连接。
尝试这样做:
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
然后不要在下一行设置CommandText
属性。
更新: Marc是对的,你甚至没有使用你的参数,因为你的查询定义不适合所谓的准备语句。试试这个:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
using (OleDbConnection myConnection = new OleDbConnection(connectionString))
{
myConnection.Open();
string query = "INSERT INTO LOGIN_TABLE (UserName, Password) VALUES (?, ?)";
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
myCommand.Parameters.Add("UserName", OleDbType.VarChar, 50);
myCommand.Parameters.Add("Password", OleDbType.VarChar, 50);
myCommand.Parameters[0].Value = textBox1.Text;
myCommand.Parameters[1].Value = textBox2.Text;
myCommand.Prepare();
myCommand.ExecuteNonQuery();
}
我摆脱了一些不必要的任务,并以不同的方式设置命令参数。试一试,让我知道是否能解决您的问题。