C# 将表单中的数据插入到访问数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19275557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Inserting Data from a form into an access Database
提问by Kentao
I started learning about C#
and have become stuck with inserting information from textboxes into an Access
database when a click button is used.
当使用单击按钮时,我开始学习C#
并将信息从文本框中插入到Access
数据库中。
The problem I get is during the adding process. The code executes the Try... Catch
part and then returns an error saying "Microsoft Access Database Engine" and doesn't give any clues.
我遇到的问题是在添加过程中。该代码执行该Try... Catch
部分,然后返回一条错误消息,指出“Microsoft Access 数据库引擎”并且没有提供任何线索。
Here is the code:
这是代码:
namespace WindowsFormsApplication1
{
public partial class FormNewUser : Form
{
public FormNewUser()
{
InitializeComponent();
}
private void BTNSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Copy Cegees\Cegees\Cegees\Login.accdb";
String Username = TEXTNewUser.Text;
String Password = TEXTNewPass.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Login (Username, Password) Values(@Username, @Password)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("@Username", OleDbType.VarChar).Value = Username;
cmd.Parameters.Add("@Password", OleDbType.VarChar).Value = Password;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
采纳答案by HansUp
Password
is a reserved word. Bracket that field name to avoid confusing the db engine.
Password
是保留字。将该字段名称括起来以避免混淆数据库引擎。
INSERT into Login (Username, [Password])
回答by David
and doesnt give any clues
并且没有给出任何线索
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
是的,不幸的是,您的代码忽略了所有这些线索。看看你的异常处理程序:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the sourceof the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
您正在检查的只是异常的来源。在这种情况下,它是“Microsoft Access 数据库引擎”。您不是在检查错误消息本身、堆栈跟踪或任何内部异常,或任何有关异常的有用信息。
Don't ignore the exception, it contains information about what went wrong and why.
不要忽略异常,它包含有关出错原因和原因的信息。
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at leastcapture the exception message, stack trace, and any inner exception(s). Currently you're ignoringthe error, which is why you're not able to solve the error.
有各种日志工具(NLog、log4net 等)可以帮助您记录有关异常的有用信息。否则,您至少应该捕获异常消息、堆栈跟踪和任何内部异常。目前您忽略了错误,这就是您无法解决错误的原因。
In your debugger, place a breakpoint inside the catch
block and examine the details of the exception. You'll find it contains a lot of information.
在您的调试器中,在catch
块内放置一个断点并检查异常的详细信息。你会发现它包含了很多信息。
回答by Pir Fahim Shah
This answer will help in case, If you are working with Data Basesthen mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
这个答案会有所帮助,如果您正在使用数据库,那么主要是借助 try-catch 块语句,这将帮助和指导您的代码。在这里,我将向您展示如何使用按钮单击事件在数据库中插入一些值。
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
回答by Ernst Blignaut
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 klass = new Form2();
klass.ShowDialog();
string my_querry = "INSERT INTO test(Sname,Ssurname,SNumber,SDNP,Sexam)VALUES('" + klass.getName() + "','" + klass.getSurname() + "','" + klass.getNumber() + "','" + klass.getDNP() + "','" + klass.getExam() + "')";
dbconn = new OleDbConnection(conn + dbfile);
dbconn.Open();
try
{
OleDbCommand cmd = new OleDbCommand(my_querry, dbconn);
cmd.ExecuteNonQuery();
MessageBox.Show("success....");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
dbconn.Close();
}
回答by Irtaza Ali
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}