我有以下代码来添加新用户:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
public class users
{
public Sqlconnection myconn ()
{
return new ("data source=.; integrated security=true; initial catalog=test;");
}
public bool insertuser(username, pass, type)
{
try {
string query="insert into users (username, pass, type) values ( '"+username+"', '"+pass+"', '"+type+"');
return true;
SqlCommand mycommand = new SqlCommand (query, this.myconn);
mycommand.Connection.Open();
mycommand.ExecuteNonQuery();
mycommand.Connection.Close();
return true;
}
catch {
return false;
}
}
}
现在在表单中,如果用户调用此方法
users user1 = new users();
if(user1.insertuser(txtusername.tex, txtpass.text, cbtype.text)==true)
{
// BUG IS HERE IF USER WRITE SOMETHING SO.. ANGEL' (WITH THIS ')
// MY CODE IS GOING TO HAVE A BUG!
// I QUIT THEM IN KEY PRESS BUT WHAT HAPPEND IF USERS MUST TO ADD SOMETHING AS
// tic's
// what can i do for my code acept all?? and it doesn't have any bug?
MessageBox.show("user added");
}
答案 0 :(得分:3)
您已重新发现SQL注入攻击。
不要在SQL中包含外部派生的值。
改为使用参数化查询。
您显示的代码无论如何都不会编译(Sqlcommand vs SqlCommand),而是阅读this MSDN page(或只是搜索有关参数化查询或SQL注入的信息)以获取更多信息。
答案 1 :(得分:3)
您的代码存在多个问题:
return true;
,这意味着它不会运行任何内容using
来保证连接关闭/处理即使发生异常试图从头开始:
public static bool InsertUser(string userName, string password, string type)
{
try
{
using (var connection = new SqlConnection("data source=.; integrated security=true; initial catalog=test;"))
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into users (username, pass, type) values (@username, @password, @type)";
command.Parameters.AddWithValue("username", userName);
command.Parameters.AddWithValue("password", password);
command.Parameters.AddWithValue("type", type);
connection.Open();
command.ExecuteNonQuery();
}
return true;
}
catch (SqlException)
{
return false;
}
}