我想将文本框值添加到访问数据库中的相关列,已建立连接,但是当我单击提交按钮时,不会添加值。 这是我试过的代码,感谢任何帮助
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
}
}
答案 0 :(得分:0)
也许在Page_Load方法中,您没有if(!isPostback),因此TextBoxes
的值会在执行postback
方法之前在Button1_Click
上重置。
答案 1 :(得分:0)
尝试使用connection string
添加OleDbCommand
。
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(@EmailAddress, @UserName, @Password)",con);
答案 2 :(得分:0)
这是一个例子,所有数据操作都驻留在一个类中。如果添加新记录成功,则返回新的主键。如果失败,您可以查询导致失败问题的异常。
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 :(得分:0)
如果EmptyWaterHole的答案不是问题,那么连接错误吗?
确保'VarChar'是每个字段的正确数据类型。
另外,请确保值不超过大小(即:如果您将字段设置为最多只允许25个字符,并且您的值超过25个字符,则不会添加该值)。
此外,如果您不允许空值并且其中一个值超出限制,则不会添加整个记录。
答案 4 :(得分:0)
先生。饥饿。试试吧。
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");
}
}
}
}
答案 5 :(得分:0)
试试这个,如果你使用 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);
}