将C#插入Microsoft Access [英] INSERT INTO c# to Microsoft access

查看:82
本文介绍了将C#插入Microsoft Access的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将某些文本框中的文本插入到我可以访问的数据库中.该代码不会产生任何错误,但似乎不会将项目添加到数据库中.

I am trying to insert the text inside some text boxes into a database that I have in access. The code produces no errors but does not seem to add the items to the database.

数据库称为数据库",表称为"TotalPlayerName",字段称为玩家名称". 表格中还有其他字段.

The Database is called 'Database' the table is called 'TotalPlayerName' and the field is called 'Player Name'. There are other fields in the table.

for(int i = 0; i < numberOfPlayers; i++){

  using (OleDbConnection connection = new OleDbConnection(@"CONNECTION STRING"){
    using (OleDbCommand command = new OleDbCommand(@"INSERT INTO TotalPlayerName ([Player Name]) VALUES(@p1)", connection)){

      connection.Open();
      command.Parameters.Add("@p1", OleDbType.VarWChar).Value = Convert.ToString(textBox[i].Text);
      command.ExecuteNonQuery();

    }

  }

}

推荐答案

虽然我看不出您的代码有什么特别的问题,但我可以告诉您您的方法有点不对劲.具体来说,对于循环的每次迭代,您都是:

While I don't see what's specifically wrong with your code, I can tell you your methodology is off a bit. Specifically, for every iteration of your loop you are:

  1. 建立与数据库的连接
  2. 创建插入命令,创建参数并分配值
  3. 执行插入

如果您一次执行步骤1和步骤2的一部分,然后在循环中执行如下语句,那将更好:

It would be better all around if you did steps 1 and part of 2 once and then executed the statement within the loop like this:

using (OleDbConnection conn = new OleDbConnection(
    @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\foo.accdb"))
{
    conn.Open();

    OleDbCommand command = new OleDbCommand(
        @"INSERT INTO TotalPlayerName ([Player Name]) VALUES (@p1)", conn);
    command.Parameters.Add(new OleDbParameter("@p1", OleDbType.VarChar));

    for (int i = 0; i < numberOfPlayers; i++)
    {
        command.Parameters[0].Value = textbox[i].Text;

        try
        {
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            // do something
        }
    }

    conn.Close();
}

我假设textbox是实际文本框控件的数组或列表.如果是这种情况,则textbox[i].Text已经是一个字符串,并且您无需执行任何特殊操作即可使OLE识别出它.

I assume textbox is an array or list of actual Text Box controls. If that's the case, then textbox[i].Text is already a string, and you shouldn't need to do anything special to make OLE recognize it as such.

最后一点-添加try/catch并在其中放置一个断点.您确定它没有失败吗?如果您在调试模式下运行,则不能保证您的程序将停止运行-它可能会返回到表单而不会报告任何错误.直到您尝试部署该应用程序时,您才可能看到实际的错误.

On a final note -- add that try/catch and put a breakpoint there. Are you SURE it's not failing? If you are running in debug mode, there is no guarantee that your program will halt -- it may just return back to the form without reporting any error. It may not be until you attempt to deploy the app that you see the actual error occurring.

这篇关于将C#插入Microsoft Access的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆