它没有错误,但它有一个消息框显示Ms Access数据库引擎和数据未插入数据库。谁能帮我解决问题?
namespace WindowsFormsApplication1
{
public partial class SignUp : Form
{
public SignUp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
OleDbCommand cmd = new OleDbCommand("INSERT INTO Register(Username,Password,Email,Address) Values(@Username, @Password,@Email,@Address)");
cmd.Connection = conn;
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("@Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("@Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("@Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("@Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
答案 0 :(得分:1)
ExecuteNonQuery()
将返回int
值,表示已更新为Database
的行数。
如果返回的值为0
,则可以显示消息DATA NOT ADDED
试试这个:写下你的try
块,如下所示。
try
{
if(cmd.ExecuteNonQuery()>0)
MessageBox.Show("DATA ADDED");
else
MessageBox.Show("DATA NOT ADDED");
conn.Close();
}
答案 1 :(得分:1)
这对希望有何帮助
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Register(Username,Password,Email,Address) Values(@Username, @Password,@Email,@Address)";
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("@Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("@Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("@Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("@Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
答案 2 :(得分:0)
将此添加到您的捕获
catch (OleDbException ex){
MessageBox.Show(ex.Message);
conn.Close();
}
并尝试再次插入,也许你现在可以看到确切的错误。
祝你好运。