我试图制作一个代码,用于检查我的表中是否有相同名称的现有记录但是我收到错误“数据类型的无效运算符。运算符等于减号,类型等于varchar”。我理解错误,但我不明白为什么我不能将它转换为int。
这是我的代码,任何使其工作的帮助将不胜感激!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string checkuser = "select count(*) from StudTable where-'" + TextBoxName.Text + "'";
SqlCommand studCom = new SqlCommand(checkuser, studConn);
int temp = Convert.ToInt32 (studCom.ExecuteScalar().ToString());
studConn.Close();
if (temp == 1)
{
Response.Write("User already exists");
}
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
try
{
Guid studGUID = Guid.NewGuid();
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string insertQuery = "insert into StudTable (ID,Name,Email,Age,Continent,School,Password) values (@ID,@name,@email,@age,@cont,@school,@pass)";
SqlCommand studCom = new SqlCommand(insertQuery, studConn);
studCom.Parameters.AddWithValue("@ID", studGUID.ToString());
studCom.Parameters.AddWithValue("@name", TextBoxName.Text);
studCom.Parameters.AddWithValue("@email", TextBoxEmail.Text);
studCom.Parameters.AddWithValue("@age", TextBoxAge.Text);
studCom.Parameters.AddWithValue("@cont", DropDownCont.SelectedItem.ToString());
studCom.Parameters.AddWithValue("@school", TextBoxSchool.Text);
studCom.Parameters.AddWithValue("@pass", TextBoxPass.Text);
studCom.ExecuteNonQuery();
Response.Redirect("Backend.aspx");
Response.Write("Your Registration is Sucessful");
studConn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" +ex.ToString());
}
}
}
谢谢!
答案 0 :(得分:2)
您需要更改命令文本并使用parameterized queries而不是字符串连接
string checkuser = "select count(*) from StudTable where Name = @Name";
SqlCommand studCom = new SqlCommand(checkuser, studConn);
studCom.Parameters.AddWithValue("@Name", TextBoxName.Text);
您应该在(-)
之后移除Where
,并使用equality operator =
来检查相等。
答案 1 :(得分:0)
在SSMS中执行插入命令时,我刚收到此错误:
我在我的sql命令中发现了一个我没有意识到的“-”(我在SSMS的插入命令中插入了很多注释“-和一些文本”,每列后都有减号) '-' 标志)。显然,该错误集中在错误的负号上。