【发布时间】:2014-04-06 20:23:21
【问题描述】:
我正在尝试编写一个代码来检查我的表中是否存在具有相同名称的现有记录,但我收到错误“数据类型的运算符无效。运算符等于减号,类型等于 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());
}
}
}
谢谢!
【问题讨论】:
-
如果要将值转换为数字,则必须在 SQL 查询中显式进行该转换,或者将其作为数字文字而不是字符串文字包含在内(或者甚至更好地使用参数将值放入查询中)。但是你为什么要把它转换成一个数字,你想做什么?您在
where子句中的条件没有任何意义,一旦您通过此错误消息,您会得到一个告诉您数字不是条件中的有效表达式的消息。 -
如果表中的名称与正在注册的名称匹配,我希望我的代码生成 1,但你是对的,它不像我预期的那样工作,我不完全确定我理解为什么。
-
当您真正想要
where Name = 'Erademus'之类的东西时,您会在查询中得到例如where-'Erademus'。
标签: c# asp.net sql sql-server sqldatatypes