ADO.NET:数据库访问技术(通过程序来连接访问数据库)
连接数据库增删改:
string cs = "server=.;user=sa;pwd=123;database=date0908";
SqlConnection con = new SqlConnection(cs);
SqlCommand com = con.CreateCommand();
//com.CommandText = "insert into student values('木婉清','0','2006-06-06')";
//com.CommandText = "delete from student where ids=12";
com.CommandText = "update student set name='阿碧' where name='虚竹'";
con.Open();
int a = com.ExecuteNonQuery();
con.Close();
if (a > 0) Console.WriteLine("成功");
else Console.WriteLine("失败"); --只能有一句执行语句
连接数据库查:
string cs = "server=.;user=sa;pwd=123;database=date0908";
SqlConnection con = new SqlConnection(cs);
SqlCommand com = con.CreateCommand();
com.CommandText = "select * from student";
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Console.Write(dr["name"]);
Console.Write("——");
Console.Write(dr["sex"]);
Console.Write("——");
Console.Write(dr["birthday"]);
Console.Write("——");
Console.WriteLine();
}
}
con.Close();
注入攻击、防御:
Console.Write("请输入要查询的用户名:");
string na = Console.ReadLine();
com.CommandText = "select * from student where name ='"+na+"'";
当输入的na为 a'delete from student -- 时,会被执行并删除数据库的信息 此为攻击
com.CommandText = "select * from student where name like @a";
com.Parameters.Clear();
com.Parameters.AddWithValue("@a", na+"%"); --防御,能够将输入的不转化为代码,此为防御,并且能够模糊查询;