Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am unable to insert in database using the following code :

C#
public static int Insert(string query)
       {
           int i=0;
           try
           {
               DBConnection.InitializeConnection(cmd);
               cmd.CommandText = query;
               cmd.CommandType = CommandType.Text;
               if (cmd.Connection.State != ConnectionState.Open)
               {
                   cmd.Connection.Open();
                   i = cmd.ExecuteNonQuery();
               }
           }
           catch (Exception)
           {
               i = 0;
           }
           finally
           {
               if (cmd.Connection.State != ConnectionState.Closed)
               {
                   cmd.Connection.Close();
               }
          }
           return i;
       }






C#
try
{
query.Append("INSERT INTO Suppliers ");
query.Append("(SupName,ConcernedPerson,MobileNum,PostalAddr,Email) ");
query.Append("VALUES("+txtSupplier.Text.ToString());
query.Append(","+txtConcerned.Text.ToString());
query.Append(","+Convert.ToInt64(txtMobile.Text));
query.Append(","+txtAddress.Text.ToString());
query.Append(","+txtEmail.Text.ToString()+");");
int i=POS.DbOperation.Insert(query.ToString());
MessageBox.Show(i.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex+""+ex.InnerException);
}



Is this method perfect to do insertion over any other method?
Thanks,
Hritik
Posted

NO!
It's wide open to SQL Injection attack which can damage or destroy your database. Use a parametrised query instead!
 
Share this answer
 
This is not a good approach to inserting data into a database as it is highly vulnerable, especially to SQL Injection attacks.

However, to get your code to work all of your string need to be within single quotes, which looking at your code appears not to be the case.

If you changed it to:

C#
query.Append("INSERT INTO Suppliers ");
query.Append("(SupName,ConcernedPerson,MobileNum,PostalAddr,Email) ");
query.Append("VALUES('"+txtSupplier.Text.ToString());
query.Append("','"+txtConcerned.Text.ToString());
query.Append("','"+Convert.ToInt64(txtMobile.Text));
query.Append("','"+txtAddress.Text.ToString());
query.Append("','"+txtEmail.Text.ToString()+"');");

Then it should work.

However I would suggest you look at using Parameters.

If you changed your Insert method to have this definition:
public static int Insert(string query, Dictionary<string,> parameters)


Then instead of how you generate your query string you could have:

C#
var insertQuery = @"INSERT INTO Suppliers (SupName, ConcernedPerson, MobileNum, PostalAddr, Email) Values (@name, @concernedPerson, @mobile, @addr, @email)


Then create you parameters dictionary as follows:
C#
var paramDic = new Dictionary<string,>();
paramDic.Add("@name", txtSupplier.Text); //Repeat this line for each parameter

Call your new insert method as
Insert(insertQuery, paramDic)

Then you need to tweak your insert command as follows:
C#
cmd.CommandText = query;
foreach(var p in parameters){
cmd.Parameters.AddWithValue(p.Key, p.Value);
}
 
Share this answer
 
Comments
Akkywadhwa 11-Sep-14 4:53am    
public static int Insert(string query,Dictionary<string,string> parameters)
{
int i=0;
try
{
DBConnection.InitializeConnection(cmd);
foreach (var p in parameters)
{
cmd.Parameters.AddWithValue(p.Key,p.Value);
}
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
i = cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
i = 0;
}
finally
{
if (cmd.Connection.State != ConnectionState.Closed)
{
cmd.Connection.Close();
}
}
return i;
}





query = "INSERT INTO Suppliers ";
query+="(SupName,ConcernedPerson,MobileNum,PostalAddr,Email) ";
query += "VALUES(@Name,@ConcernedPerson,@Mobile,@Postal,@Email)";
var param = new Dictionary<string,string>();
param.Add("@Name", txtSupplier.Text.ToString());
param.Add("@ConcernedPerson", txtConcerned.Text.ToString());
param.Add("@Mobile", txtMobile.Text.ToString());
param.Add("@Postal", txtAddress.Text.ToString());
param.Add("@Email", txtEmail.Text.ToString());
int i= POS.DbOperation.Insert(query, param);
MessageBox.Show(i.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex+""+ex.InnerException);
}
}



This too doesn't work.
Hritik
Pheonyx 11-Sep-14 5:11am    
What error are you getting?
Akkywadhwa 11-Sep-14 6:03am    
Object reference not set to an instance of an object.
System Null Reference Exception
Pheonyx 11-Sep-14 6:04am    
Have you debugged your code to see where the error is occurring, on what line. You should do that and see which object is null.
Akkywadhwa 11-Sep-14 11:18am    
Its on line "int i= POS.DbOperation.Insert(query, param);"
You should look into DbCommand[^] and DbParameter[^] instead.
It is much safer than using concatenated strings.

Configuring Parameters and Parameter Data Types[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900