C# 我能';t将.NET中的数据添加到Access 2010
按钮。单击事件:C# 我能';t将.NET中的数据添加到Access 2010,c#,asp.net,oledb,ms-access-2010,C#,Asp.net,Oledb,Ms Access 2010,按钮。单击事件: OleDbConnection db_conn; db_conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\veri.accdb;Persist Security Info=False"); try { db_conn.Open(); OleDbCommand db_command = new OleDbCommand("
OleDbConnection db_conn;
db_conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\veri.accdb;Persist Security Info=False");
try
{
db_conn.Open();
OleDbCommand db_command = new OleDbCommand("Insert INTO data(Name,Mail) Values( '" + TextBox1.Text + "','" + TextBox2.Text + "')", db_conn);
db_command.ExecuteNonQuery();
db_conn.Close();
Label5.Text = "Succesfully!";
}catch{
Response.Write("There is something wrong!");
}
- 结果是:有问题
- 我的IDE是Visual Studio 2012
- 我的访问版本是2010
- 我的数据库名是veri.accdb
db_conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\veri.accdb;Persist Security Info=False");
当您有反斜杠这样的特殊字符时,字符串前面的简单@是必需的。(或使用两个反斜杠,如C:\\veri.accdb
)
说你还有一个问题。C:驱动器的根目录不是放置数据库的好位置,因为它需要特殊权限,并且通常是只读的
最后,字符串连接是一种非常糟糕的做法,应该改为参数化查询
string cmdText = "Insert INTO data(Name,Mail) Values(?,?)";
using(OleDbConnection db_conn = new OleDbConnection(@"......."))
using(OleDbCommand db_command = new OleDbCommand(cmdText, db_conn))
{
try
{
db_conn.Open();
db_command.Parameters.AddWithValue("@p1",TextBox1.Text);
db_command.Parameters.AddWithValue("@p2",TextBox2.Text);
db_command.ExecuteNonQuery();
Label5.Text = "Succesfully!";
}
catch(Exception ex)
{
// It is preferable to not catch the exception if you don't do anything,
// but if you catch then, at least, report what is wrong
Response.Write("There is something wrong!" + ex.Message);
}
}
您应该抛出真正的异常以找出问题所在。捕获实际异常:Catch(exception ex){}..然后查看您收到的消息。不要在根驱动器中使用异常、SQL注入、数据库。这里有很多问题。永远不要使用太糟糕的字符串。为了安全起见,请使用参数。你确定那个文本框得到信息了吗?也许是空的