private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
int b = int.Parse(textBox2.Text);
bool bl = ceshi(a, b);
if (bl)
{
MessageBox.Show("成功");
}
else
{
MessageBox.Show("SHIBAI");
}
}
public bool ceshi(string a, int b)
{
string sqlconnectionstring = "server=localhost;database=ceshi;integrated security=SSPI";
SqlConnection con = new SqlConnection(sqlconnectionstring);
con.Open();
//string commandtext = "select * from Table_1 where name=@name and passward=@passward";
string commandtext = "select * from Table_1 where name=" + a + "and passward=" + b;
SqlCommand cmd = new SqlCommand(commandtext, con);
//cmd.Parameters.Add("@name", SqlDbType.VarChar);
//cmd.Parameters["@name"].Value = "a";
//cmd.Parameters.Add("@passward", SqlDbType.Int);
//cmd.Parameters["@passward"].Value = b;
//SqlDataAdapter adapter = new SqlDataAdapter(cmd);
//DataSet ds = new DataSet();
//adapter.Fill(ds);
//return ds.Tables.Count;
SqlDataReader reader = cmd.ExecuteReader();
//return reader.HasRows;
if (reader.Read())
{
return true;
}
else
{
return false;
}
con.Close();
}我在数据库建的字段name 为varchar,passward为int,提示说passward附近有错误
string commandtext = "select * from Table_1 where name='" + a + "' and passward=" + b;
name是varchar 就要''
而且与and之间要一个空格
string commandtext = "select * from Table_1 where name=" + a + "and passward=" + b;
a前后加单引号
字符串类型要加单引号,其它不加。
PS:密码怎么会为整型呢。
string类型加上‘ ’
原: string commandtext = "select * from Table_1 where name=" + a + "and passward=" + b;
新: string commandtext = "select * from Table_1 where name=‘’" + a +“' " + "and passward=" + b;
其实这样的字符串操作最好是用 StringBuilder 类来做。效率高些、也更节约资源。
好好的参数化查询的代码,楼主不用,还非要去拼SQL,为啥呢?
如果你的sql里已经用单引号将name括起来了,那你可以开始考虑注入的问题了,比如用户名里是不是有单引号?这样拼SQL是很危险的.
string commandtext = "select * from Table_1 where name='" + a + "' and passward=" + b"';
我刚学的时候碰见股这样的问题
后来先在SQLSercer试验好语句再加到VS里边
再后来,熟悉了就直接写了
呵呵