【问题标题】:How do i add textbox values to Access database?如何将文本框值添加到 Access 数据库?
【发布时间】:2018-04-17 00:38:50
【问题描述】:

我想将文本框值添加到 access 数据库中的相关列,连接已经建立,但是当我单击提交按钮时,没有添加值。 这是我尝试过的代码,感谢任何帮助

protected void Button1_Click(object sender, EventArgs e)
{
    string EmailAddress = TextBox1.Text;
    string UserName = TextBox2.Text;
    string Password = TextBox3.Text;

    try
    {
        OleDbConnection con = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");

        OleDbCommand cmd = new OleDbCommand();
        cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(@EmailAddress, @UserName, @Password)");
        con.Open();


         if (con.State == ConnectionState.Open)
         {
             TextBox1.Text = "sssss";

             cmd.Parameters.Add("@EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
             cmd.Parameters.Add("@UserName", OleDbType.VarChar).Value = TextBox2.Text;
             cmd.Parameters.Add("@Password", OleDbType.VarChar).Value = TextBox3.Text;

            cmd.ExecuteNonQuery();
            con.Close();

         }


    }
    catch (Exception error)
    {
        //Show error message as    error.Message
    }

}

【问题讨论】:

    标签: c# asp.net .net vb.net ms-access


    【解决方案1】:

    尝试添加connection stringOleDbCommand

    cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(@EmailAddress, @UserName, @Password)",con);
    

    【讨论】:

      【解决方案2】:

      这是一个示例,所有数据操作都驻留在一个类中。如果添加新记录成功,则返回新的主键。失败时,您可以查询引发失败问题的异常。

      using System;
      using System.Windows.Forms;
      using System.Data.OleDb;
      using System.IO;
      
      namespace MS_AccessAddNewRecord_cs
      {
          public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
      
              private void addRecordButton_Click(object sender, EventArgs e)
              {
                  var ops = new Operations();
                  var newId = 0;
                  if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
                  {
                      newIdentifierTextBox.Text = $"{newId}";
                  }
                  else
                  {
                      MessageBox.Show($"{ops.Exception.Message}");
                  }
              }
          }
          /// <summary>
          /// This class should be in a separate class file, I placed it here for easy of learning
          /// </summary>
          public class Operations
          {
              private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
              {
                  Provider = "Microsoft.ACE.OLEDB.12.0",
                  DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
              };
      
              private Exception mExceptiom;
              public Exception Exception
              {
                  get
                  {
                      return mExceptiom;
                  }
              }
              /// <summary>
              /// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
              /// </summary>
              /// <param name="pName"></param>
              /// <param name="pContactName"></param>
              /// <param name="pContactTitle"></param>
              /// <param name="pIdentfier"></param>
              /// <returns></returns>
              public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
              {
                  bool Success = true;
      
                  try
                  {
                      using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
                      {
                          using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
                          {
                              cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " + 
                                                                "Values(@CompanyName,@ContactName, @ContactTitle)";
      
                              cmd.Parameters.AddWithValue("@CompanyName", pName);
                              cmd.Parameters.AddWithValue("@ContactName", pContactName);
                              cmd.Parameters.AddWithValue("@ContactTitle", pContactTitle);
      
                              cn.Open();
      
                              int Affected = cmd.ExecuteNonQuery();
      
                              if (Affected == 1)
                              {
                                  cmd.CommandText = "Select @@Identity";
                                  pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
                              }
                          }
                      }
                  }
                  catch (Exception ex)
                  {
                      Success = false;
                      mExceptiom = ex;
                  }
      
                  return Success;
      
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        也许在 Page_Load 方法中您没有 if(!isPostback),因此在执行 Button1_Click 方法之前,TextBoxes 的值会在 postback 上重置。

        【讨论】:

          【解决方案4】:

          如果 EmptyWaterHole 的回答不是问题,是不是连接出错了?

          确保“VarChar”是每个字段的正确数据类型。

          此外,请确保值不超过大小(即:如果您将字段设置为最多允许 25 个字符并且您的值超过 25 个字符,则不会添加该值)。

          此外,如果您不允许空值并且其中一个值超出限制,则不会添加整条记录。

          【讨论】:

            【解决方案5】:

            先生。饥饿的。像这样试试。

            using System;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.Data;
            using System.Drawing;
            using System.Linq;
            using System.Text;
            using System.Windows.Forms;
            using System.Data.OleDb;
            
            namespace WindowsFormsApplication2
            {
                public partial class Form1 : Form
                {
                    public Form1()
                    {
                        InitializeComponent();
                    }
            
                    private void button1_Click(object sender, EventArgs e)
                    {
            
                        OleDbConnection conn;
                        conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
            
                        conn.Open();
            
                        OleDbCommand cmd = conn.CreateCommand();
            
                        cmd.CommandText = @"INSERT INTO MyExcelTable([Fname], [Lname],  [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
                        cmd.ExecuteNonQuery();
                        conn.Close();
            
                    }
            
                    public OleDbConnection myCon { get; set; }
            
                    private void button2_Click(object sender, EventArgs e)
                    {
            
                        OleDbConnection conn = new OleDbConnection();
                        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
            
                        string fstName  = textBox1.Text.Trim();
                        string lstName  = textBox2.Text.Trim();
                        string adres = textBox3.Text.Trim();
                        OleDbCommand cmd = new OleDbCommand(@"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (@FName, @LName, @Address)")
                        {
                            Connection = conn
                        };
            
                        conn.Open();
            
                        if (conn.State == ConnectionState.Open)
                        {
                            // you should always use parameterized queries to avoid SQL Injection
                            cmd.Parameters.Add("@FName", OleDbType.VarChar).Value = fstName;
                            cmd.Parameters.Add("@LName", OleDbType.VarChar).Value = lstName;
                            cmd.Parameters.Add("@Address", OleDbType.VarChar).Value = adres;
            
                            try
                            {
                                cmd.ExecuteNonQuery();
                                MessageBox.Show(@"Data Added");
                                conn.Close();
                            }
                            catch (OleDbException ex)
                            {
                                MessageBox.Show(ex.Source + "\n" + ex.Message);
                                conn.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show(@"Connection Failed");
                        }
                    }
                    }
                }
            

            【讨论】:

              【解决方案6】:

              如果你使用 access 作为你的数据库,试试这个它会起作用

              try
              {
                  OleDbCommand command = new OleDbCommand();
                  command.Connection = connection;
                  command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(@patientName,@tel,@hostel,@id no,@department,@diagnose,@gender)";
                  connection.Open();
                  command.Parameters.AddWithValue("@patientName", textBox1.Text);
                  command.Parameters.AddWithValue("@tel", textBox2.Text);
                  command.Parameters.AddWithValue("@hostel", textBox3.Text);
                  command.Parameters.AddWithValue("@id no", textBox4.Text);
                  command.Parameters.AddWithValue("@department", textBox5.Text);
                  command.Parameters.AddWithValue("@diagnose", richTextBox1.Text);
                  command.Parameters.AddWithValue("@gender", textBox6.Text);
                  command.ExecuteNonQuery();
                  connection.Close();
                  MessageBox.Show("Patient record Have been save successfully....");
              
              }
              catch (Exception ex)
              {
                  MessageBox.Show("error" + ex);
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-02-03
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多