【问题标题】:Inserting records into a Microsoft Access database in C#在 C# 中将记录插入 Microsoft Access 数据库
【发布时间】:2011-02-23 06:31:47
【问题描述】:

我正在插入数据以使用 C# 访问 2000-2003 文件格式数据库。当我有一个包含 2 个字段的数据库时,查询工作正常,但当有更多字段时,它就不起作用了。

我有两个相同的代码,我无法找到问题。

using System.Data.OleDb;    // By using this namespace I can connect to the Access Database.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private OleDbConnection myconn;
        public Form1()
        {
            InitializeComponent();
            myconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\NewManageContacts.mdb");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
           // this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
            // TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
            this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);

        }


        private void button1_Click(object sender, EventArgs e)
        {
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
           // string query = "insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
            cmd.CommandText = @"insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text +  "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
            cmd.Connection = myconn;
            myconn.Open();
            cmd.ExecuteNonQuery();
            System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            myconn.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
            textBox8.Text = "";

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

    }
}

这是只有 2 个字段的表格的代码

public partial class Form1 : Form
{
    private OleDbConnection myCon;
    public Form1()
    {
        InitializeComponent();
        myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\Database1.mdb");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'database1DataSet.Table1' table. You can move, or remove it, as needed.
        this.table1TableAdapter.Fill(this.database1DataSet.Table1);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into Table1 (name,fname) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
        cmd.Connection = myCon;
        myCon.Open();
        cmd.ExecuteNonQuery();
        System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
        myCon.Close();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        textBox2.Text = "";
    }
}

【问题讨论】:

  • SQL 注入漏洞。使用参数化查询,而不是直接从用户输入连接您的 SQL 字符串。
  • @thomas 你能举个例子吗?为什么有 2 个字段的表没有问题?
  • 你能发布你得到的错误吗?此外,您要插入到联系人中的值是否包含单引号(即 ')?
  • “它不工作”是什么意思?你有例外吗?如果是这样,请提供异常详细信息 - 将来您应该尝试发布有关您的问题的具体问题,而不是大量代码。
  • @user561730 - 正如其他人所提到的,我们需要更多信息来回答有关错误的问题。至于 SQL 注入,您的查询应该看起来像 insert into Table1 (name,fname) values (@name, @fname),然后您调用 cmd.AddParameterWithValue( "@name", textbox1.Text); 和类似的 fname。切勿将用户条目中的值直接连接到 SQL 语句中。

标签: c# ms-access


【解决方案1】:

您尝试插入的额外字段可能具有不易连接到有效 SQL 语句中的值。例如:

string field1 = "meh";
string field2 = "whatever";
string field3 = "'Ahoy!' bellowed the sailor.";
var cmd = new SqlCommand(
    "INSERT INTO blah (x, y, z) VALUES ('" + field1 + "', '" + field2 + "', '" + field3 + '")");

根据上述输入,想象一下连接的 SQL 会是什么样子。

更糟糕的是,想象一下如果有人在您的表单中输入此 SQL,您将要执行的 SQL:

field3 = "Bobby'); DROP TABLE Users; -- ";

通过cmd.Parameters.AddAddRange 使用参数化查询(描述为here)。上面的例子可以这样修改:

var cmd = new SqlCommand("INSERT INTO blah (x, y, z) VALUES (@x, @y, @z)");
cmd.Parameters.AddRange(new[] {
    new SqlParameter("@x", field1),
    new SqlParameter("@y", field2),
    new SqlParameter("@z", field2)
    });

【讨论】:

  • OleDbParameter myParm = cmd.Parameters.Add("@fname", OleDbType.VarChar, 50); myParm.Value = textBox1.Text; myParm = cmd.Parameters.Add("@lname", OleDbType.VarChar, 50); myParm.Value = textBox2.Text;这是否为我解决了问题?
【解决方案2】:

此代码公开:

OleDbConnection con = new OleDbConnection(@"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Mohammadhoseyn_mehri\Documents\Data.mdb");

这个singup按钮的代码:

 try
 {
     createaccount();
     else
     {
         MessageBox.Show("Please re-enter your password");
     }
 }
 catch(Exception ex)
 {
     MessageBox.Show(ex.Message);
 }
 finally
 {
     MessageBox.Show("Data saved successfully...!");
     con.Close();
}

这是创建账户方法的代码:

OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Login", con);
con.Open();

String ticketno = textBox2.Text.ToString();
String Purchaseprice = textBox1.Text.ToString();
String my_query = $"INSERT INTO Login (username, pass) VALUES ('{ticketno}', '{Purchaseprice}')";

OleDbCommand cmd = new OleDbCommand(my_query, con);

cmd.ExecuteNonQuery();

【讨论】:

    【解决方案3】:

    如果您正在使用数据库,则主要使用 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_query = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
             
                OleDbCommand cmd = new OleDbCommand(my_query, conn);
                cmd.ExecuteNonQuery();
    
                MessageBox.Show("Data saved successfuly...!");
              }
             catch (Exception ex)
             {
                 MessageBox.Show("Failed due to"+ex.Message);
             }
             finally
             {
                 conn.Close();
             }
    

    【讨论】:

    【解决方案4】:
    private void btnSave_Click(object sender, EventArgs e)**
    {
       OleDbCommand cmd = new OleDbCommand();
       cmd.CommandType = CommandType.Text;
       cmd.CommandText = @"insert into Personal (P_name, P_add,P_Phone)VALUES('" + txtName.Text + "','" +txtAddress.Text + "','" + txtPhone.Text + "')";
       cmd.Connection = con;
       con.Open();
       cmd.ExecuteNonQuery();
       System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
       con.Close();
       txtName.Text = "";
       txtAddress.Text = "";
       txtPhone.Text = "";
    }
    

    【讨论】:

    • SQl 注入,使用参数化查询,如果合理,则始终使用,如果是用户输入,则无一例外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多