简体   繁体   English

通过C#将记录添加到MS Access数据库

[英]Adding records to MS Access database through C#

I am attempting to add items to an Access database in C#. 我试图将项目添加到C#中的Access数据库。 I have code that seems to work (I can open and close a database), but the button click event produces errors. 我的代码似乎正常工作(可以打开和关闭数据库),但是按钮单击事件会产生错误。 I have been searching on Google for the whole afternoon but no joy. 我整个下午都在Google上搜索,但没有任何乐趣。 My code is: 我的代码是:

private void button26_Click(object sender, EventArgs e)
{  //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value',   'Default','Type')    VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert"; 
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}

And the error I get is: 我得到的错误是:

Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized. 错误System.InvalidOperationException:ExecuteNonQuery:连接属性尚未初始化。
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method) 在System.Data.OleDb.OleDbCommand.ValidateConnection(字符串方法)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method) 在System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String方法)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) 在System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior行为,String方法)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() 在System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\\Somepath\\Form1.cs:line 49 在C:\\ Somepath \\ Form1.cs:line 49中的CrewCheifSettingsBeta3.Form1.button26_Click(Object sender,EventArgs e)

Clearly something wrong with the connection string, and that it's not SQL-injection proof either. 显然,连接字符串出了点问题,它也不是SQL注入证明。

The problem is well known. 这个问题是众所周知的。 A command need to know the connection to use to execute the command text. 命令需要知道用于执行命令文本的连接。 However you have other problems in your code. 但是,您的代码中还有其他问题。

Connection objects (like commands) should not be global, but created when they are needed and destroyed after. 连接对象(如命令)不应是全局的,而应在需要时创建并在之后销毁。 The using statement is very usefull here because you don't have to explicitly close and destroy these objects and you will never have resource leaks when an exception occurs. using语句在这里非常有用,因为您不必显式关闭和销毁这些对象,并且在发生异常时永远不会发生资源泄漏。

Second, when you use field names that are also reserved keywords in your database you should enclose these name in some kind of escape characters. 其次,当您使用字段名称也是数据库中的保留关键字时,应使用某种转义符将这些名称括起来。 These characters for Access are the open/close brackets not the single quote. Access的这些字符是左/右括号,而不是单引号。

private void button26_Click(object sender, EventArgs e)
{  
    try
    {
        string cmdText = @"INSERT INTO Main
                          ([Prop], [Value], [Default],[Type])    
                          VALUES('one', 'Kelly', 'Jill','one')";
        using(OleDbConnection connection = new OleDbConnection(.....))
        using(OleDbCommand cmd = new OleDbCommand(cmdText, connection))
        {            
            connection.Open();
            cmd.ExecuteNonQuery();
            button26.Text = "Done Insert"; 
            button26.ForeColor = Color.Lime;
            mainDataGridView.Visible = true;
        }
    }
    catch (Exception ex)
    {
        richTextBox1.Text=("Error "+ex);
        button26.ForeColor = Color.Black;
    }
}

Finally I don't know if your fields are of text type. 最后,我不知道您的字段是否为文本类型。 You pass literal texts so they should be of text type and remember to use parameters when you switch this simple code to your actual values. 您传递文字文本,因此它们应为文本类型,并在将此简单代码切换为实际值时记住使用参数。

Assign Connection property as below line. 如下行分配连接属性。

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;

Per @Steve's comment, there is no connection associated with the command when you just instantiate it like that. 根据@Steve的注释,仅以这种方式实例化该命令时,该命令就没有任何关联。 You need to either set the Connection property of the command or better yet use connection.CreateCommand() to create the command in the first place in which case it will already be associated with the connection (cleaner). 您需要设置命令的Connection属性,或者最好使用connection.CreateCommand()首先创建命令,在这种情况下,该命令已经与连接关联(更干净)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM