目前我在c#& amp; asp.net web OOP学习。 我已经编写了插入数据的代码到Microsoft Access,无论我如何尝试数据永远不会插入我的数据库,虽然代码是正确的。
在其他项目中,我使用相同的方法来做工作...... 希望有人可以在这里提供帮助。谢谢。
using System.Data.OleDb;
public class DataBaseCon
{
private static OleDbConnection GetConn()
{
string ConString;
ConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\user\Desktop\YogaDB.accdb";
return new OleDbConnection(ConString);
}
public static void Register(string un, string pw, DateTime dob, int ye, string hissue, string email, string contact)
{
OleDbConnection myConnection = GetConn();
string myQuery = "INSERT INTO User( Username, Password, DateOfBirth, YogaExp, HealthIssue, Email, Contact, UserType) VALUES ( '" + un + "' , '" + pw + "' , '" + dob + "' , '" + ye + "', '" + hissue + "' , '" + email + "', '" + contact + "', 'student')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
}
按钮功能在这里:
protected void RegisterBtn_Click(object sender, EventArgs e)
{
string un = TextBox1.Text;
string pw = TextBox2.Text;
DateTime dob = Calendar1.SelectedDate;
int ye = int.Parse(TextBox4.Text);
string hissue = TextBox5.Text;
string email = TextBox6.Text;
string contact = TextBox7.Text;
DataBaseCon.Register(un, pw, dob, ye, hissue, email, contact);
Label8.Text = "Congratulation "+ un +" , success to register!";
}
答案 0 :(得分:1)
使用命令参数,它将保护您免受Sql注入,并且您将避免这样的问题。用户是Access
中的保留字,因此您应该像[User]
一样将其转义。
string myQuery = @"
INSERT INTO
[User] ( Username, [Password], DateOfBirth, YogaExp, HealthIssue, Email, Contact, UserType)
VALUES ( @UserName, @Password, @DateOfBirth, @YogaExp, @HealthIssue, @Email, @Contact, @UserType)";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.Parameters.AddWithValue("@UserName", un);
myCommand.Parameters.AddWithValue("@Password", pw);
myCommand.Parameters.AddWithValue("@DateOfBirth", dob );
myCommand.Parameters.AddWithValue("@YogaExp", ye );
myCommand.Parameters.AddWithValue("@HealthIssue", hissue );
myCommand.Parameters.AddWithValue("@Email", email );
myCommand.Parameters.AddWithValue("@Contact", contact );
myCommand.Parameters.AddWithValue("@UserType", "student");
请注意OleDbCommand
中没有命名参数,因此您必须以与查询相同的顺序定义参数!
这是Reserved words in MS Access - > User
是他们的一部分,所以你应该逃避它!
删除这部分代码,您正在吃掉异常!
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
像这样写:
catch
{
throw;
}
编辑:就像@GordThompson一样,Password
也是保留字,所以你也应该逃避它!