...
using System.Data;
using System.Data.OleDb;
namespace accessloginapp
{
public partial class Ramen : Form
{
private OleDbConnection connection = new OleDbConnection();
public Ramen()
{
InitializeComponent();
connection.ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\...\Users.accdb;Persist Security Info=False;";
}
private void btn_Save_Click(object sender, EventArgs e)
{
try{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText =
"insert into userdata (Username,[Password]) values('" +
txt_Username + "','" + txt_Password + "')";
command.ExecuteNonQuery();
MessageBox.Show("Users added and saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
如果我不太了解,我很抱歉,我很擅长这个。当我在我的应用程序中保存用户名和密码等数据时,数据会按照我输入的内容插入但添加了文本,例如:我会发送要插入的用户名"Mark"
,但是当我去查看我的时候数据库,它被放入"System.Windows.Forms.TextBox, Text: Mark"
。如何将其更改为仅插入用户名I输入?
答案 0 :(得分:3)
您需要使用文本框控件的Text
属性来获取存储的实际文本: -
command.CommandText = "insert into userdata (Username,[Password])
values('" + txt_Username.Text + "','" + txt_Password.Text + "')";
除此之外,请注意您的查询对SQL Injection attack开放。
所以,你应该使用像这样的参数化查询: -
command.CommandText = "insert into userdata (Username,[Password])
values(?,?)";
command.Parameters.Add("?",OleDbType.VarChar,20).Value = txt_Username.Text;
并为@Password
添加参数。