我有这个表,我将其命名为Users,每当用户使用注册表单时,我想向Users.table插入他输入的所有凭据。问题是,不知何故,数据库正在尝试将用户名(列)从varchar转换为int。这是我的插入查询:
string Query = "Insert into Users(FirstName, LastName, Username,
Password, Role, Email, Class) values('" + txtfn.Text + "',
'" + txtsn.Text + "','" + txtUsername.Text + "','" + txtPassword.Text + "',
'" + cbRole.Text + "','" + txtEmail.Text + "','" + cbClass.Text + "')";
The error that pops-ups everytime a user is trying to sign up
如何防止此转换发生或以其他方式处理此错误? 在此先感谢。
答案 0 :(得分:2)
以下是如何使用SQL参数并指定类型。哪个更安全,更精确,还可以处理某些类型的转换(例如DateTime):
string Query = "Insert into Users(FirstName, LastName, Username, "
+ " Password, Role, Email, Class) "
+ " values(@fn, @sm, @user, @ps, @role, @email, @class)";
SqlCommand sqlcom = new SqlCommand(Query, sqlconnection);
// change the types to match SQL Column data types
// I set all as Nvarchar as a sample
var fnParma = new SqlParameter("@fn", SqlDbType.NVarChar);
var smParma = new SqlParameter("@sm", SqlDbType.NVarChar);
var userParma = new SqlParameter("@user", SqlDbType.NVarChar);
var psParma = new SqlParameter("@ps", SqlDbType.NVarChar);
var roleParma = new SqlParameter("@role", SqlDbType.NVarChar);
var emailParma = new SqlParameter("@email", SqlDbType.NVarChar);
var classParma = new SqlParameter("@class", SqlDbType.NVarChar);
// Here set each value by converting it to the specified type.
fnParma.Value = txtfn.Text;
smParma.Value = txtsn.Text;
// Continue for all the params. If you have int column use Int32.Parse(Text);
sqlcom.ExecuteNonQuery();
答案 1 :(得分:0)
sql表中的username
列需要整数,这里传递字符串。因此,请将表中的username
列数据类型更改为varchar
。它会工作正常。希望很清楚。