Bug for simple quotation marks in connection to database
I have the following code to add a new user:
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;
}
}
}
now in the form if user calls to this method
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?? an开发者_StackOverflow社区d it doesn't have any bug?
MessageBox.show("user added");
}
There is more than one issue with your code:
- the second line in your code sample is
return true;
, which means it will not run anything - method parameters in InsertUsers do not have type specified
- don't keep connection open, dispose connection after data are retrieved
- use
using
to guarantee connection closing/disposal even if exception happened - use parametrized query. Find here why: SQL injection.
- don't catch all exceptions, SqlException only in this case
Tried to make it from scratch:
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;
}
}
You've rediscovered SQL injection attacks.
Don't include externally-derived values in your SQL.
Use parameterized queries instead.
The code you've shown wouldn't compile anyway (Sqlcommand vs SqlCommand) but read this MSDN page (or just search for information on parameterized queries or SQL injection) for more information.
精彩评论