几个小知识点(返回自动增长的ID 带参数的SQL)

1、返回自动增长的ID

insert into mytable output inserted.ID values ('abc','cde',1)

使用 command对象有executescalar 方法 ,返回ID号

  object autoid = command.executescalar();

2、sqldatareader对象访问索引

  reader.getString(索引)

  reader.getInt32(索引)

3、SQL带参数

原始SQL语句:select count(*) from tbusers where username='abc' and userpass='abc'
注入后的SQL:select count(*) from tbusers where username='abc' or 1=1 -- and userpass='abc'

注入SQL后,会绕过注册验证,所以建议使用带参数的sql或者存储过程.

string connstr="Data source=.;Initial Catalog=mydb;Integrated Security=true";

using(SqlConnection conn = new SqlConnection(connstr))

{

  //不再拼接SQL语句,使用变量 ,变量以@来标志

  string sql="select * from tbusers where username=@username and userpass=@userpass";

  using(SqlCommand command = new SqlCommand(sql,conn))

  {

    SqlParameter paramUsername = new SqlParameter("@username",SqlDbType.VarChar,50){value=txtUsername.text};
    SqlParameter paramUserpass = new SqlPatameter("@userpass",SqlDbType,VarChar,50){value=txtUserpass.text};
    command.Parameters.add(paramUsername);
    command.Parameters.add(paramUserpass);
    conn.open();
    object result = command.executescalar();
  }

}

多参数的另一种简便写法,使用数组的形式

SqlParam[] params = new SqlParam[]
{
  new SqlParameter("@username",SqlDbType.VarChar,50){value=txtUsername.text},
  new SqlPatameter("@userpass",SqlDbType,VarChar,50){value=txtUserpass.text}
};
command.Parameters.AddRange(params);

另一个简便写法:

command.Parameters.AddWithValues("@username",txtUsername.text);

command.Parameters.AddWithValues("@userpass",txtUserpass.text);

 

posted @ 2020-04-25 11:42  boenotuch  阅读(303)  评论(0编辑  收藏  举报