How to Insert C# values to MySql? - c#

I want to insert C# winform values to Mysql
there are 3 columns
name,id are TextBox text and gender is ComboBox value
but there is error and error messsage said: MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '',')' at line 1'
what code should i fix?
using (MySqlConnection conn2 = new MySqlConnection(strconn))
{
conn2.Open();
string query = "INSERT INTO student1(name,id,gender) values ('" + name3.Text + "'," + id3.Text + "'," + gender3.SelectedValue+"');";
MySqlCommand cmd = new MySqlCommand(query, conn2);
cmd.ExecuteNonQuery();
}

You're missing a single quote in the connecting string literal between name3.Text and id3.Text and again between id3.Text and gender3.SelectedValue
But it shouldn't matter. If you're concatenating user-supplied strings like this it's only a matter of time until your system is breached. There's a better way that avoids this risk, makes it easier to get your SQL statements correct, and runs faster.
//This could be marked const!
string query = "INSERT INTO student1(name,id,gender) values (#name, #id, #gender);";
using (var conn2 = new MySqlConnection(strconn))
using (var cmd = new MySqlCommand(query, conn2))
{
//I have to guess, but you can find exact column types/lengths from your db
//Do not use AddWithValue()!
// MySql is less at risk for the AddWithValue() performance issues
// than Sql Server but the risk isn't completely eliminated.
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = name3.Text;
cmd.Parameters.Add("#id", MySqlDbType.VarChar, 50).Value = id3.Text;
cmd.Parameters.Add("#gender", MySqlDbType.VarChar, 5).Value = gender3.SelectedValue;
conn2.Open();
cmd.ExecuteNonQuery();
}

using (MySqlConnection conn2 = new MySqlConnection(strconn))
{
String query = "INSERT INTO student1(name,id,gender) values (#name,#id,#gender)";
MySqlCommand = new MySqlCommand(query, conn2);
command.Parameters.AddWithValue("#name", name3.Text);
command.Parameters.AddWithValue("#id", id3.Text);
command.Parameters.AddWithValue("#gender", gender3.SelectedValue.ToString());
command.ExecuteNonQuery();
}
use need use parameters

Related

How to Insert data into a MSSQL table using C#

I'm trying to using INSERT to write some data to a MSSQL Database table. I believe my SQL string is correct but I'm getting an error message when I run command.ExecuteScaler(); I've attached the error message in a screen shot. It states I'm using incorrect syntax but I'm not getting any compiler errors.
I'm assuming I'm just doing something wrong.
CODE:
using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
connection.Open();
String insert = #"INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer) VALUES(" + skills.SkillName + "," + skills.SkillNumber + "," + skills.LastUpdated + "," + skills.CallServer +")";
SqlCommand command = new SqlCommand(insert, connection);
command.ExecuteScalar();
connection.Close();
}
Error Message from exception pop up
Question:
What is the proper way of inserting data into a MSSQL database table?
You should be using Parameters to prevent SQL Injection.
The below code takes care of that:
var query = "INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer)
VALUES (#SkillName, #SkillNumber, #SkillLastUpdated, #SkillServer)";
using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
using(SqlCommand cmd = new SqlCommand(query, connection))
{
// add parameters and their values
cmd.Parameters.Add(new SqlParameter("SkillName", skills.SkillName ));
cmd.Parameters.Add(new SqlParameter("SkillNumber", skills.SkillNumber ));
cmd.Parameters.Add(new SqlParameter("SkillLastUpdated", skills.LastUpdated ));
cmd.Parameters.Add(new SqlParameter("SkillServer", skills.CallServer
cn.Open();
cmd.ExecuteNonQuery();
}
}
you forgot to set the connection property for the command object: command.Connection = connection;
and:
command.CommandType = CommandType.Text;
command.CommandText = your_sql_query;
See: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

C# Form Application - Saving Data to access database

As a group we are working on a project and need to save the data collected in the label in a field in an access database. However we have been having some troubles with this function.
Here is the code what i have tried so far:
We changed the values from lbl.View.text to "1" for testing purposes, but still no luck.
private void complete_btn_Click(object sender, EventArgs e)
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = connStr;
OleDbCommand cmd = con.CreateCommand();
// error is in insert statement somehwhere.
cmd.CommandText = "INSERT INTO Users (TimeStamp, Interest, TotalTime)" + "VALUES('" + "1" +"', '"+ "1" + "','" + "1" + "');";
// conn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True");
// cmd = new OleDbCommand("", con);
// cmd.Parameters.AddWithValue("#TimeStamp", lblView.Text);
// cmd.Parameters.AddWithValue("#Interest", lblView.Text);
// cmd.Parameters.AddWithValue("#TotalTime", lblView.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Based on your exception message, TimeStamp is a reserved keyword in MS Access. You need to use it with square brackets like [TimeStamp]. As a better way, change it to non-reserved word which is meaningful for your column.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO Users (TimeStamp, Interest, TotalTime)
VALUES(?, ?, ?)";
cmd.Parameter.AddwithValue("#p1", "1");
cmd.Parameter.AddwithValue("#p2", "1");
cmd.Parameter.AddwithValue("#p3", "1");
con.Open();
cmd.ExecuteNonQuery();
}

Adding rows to a SQL Server database from data entered by user in asp.net c#

string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, Sur-Name, Score,Avg) VALUES ('" + fName + "','" + sName + "','" + lblScore.Text + "','" + lblAvg.Text + "');");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#Sur-Name", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
finally
{
connection.Close();
}
The error I keep getting is a runtime saying
Incorrect syntax near '-'. Incorrect syntax near '-'.
I used the try catch just so page would load and my scores show but the label says this Incorrect syntax as well, I was wondering could anyone please help me with what I am doing wrong
Thanks.
I think Sur-Name breaks your query. Use it with square brackets like [Sur-Name]
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. I see you tried to use but you never declare your parameter names in your query.
Also DATA might be a reserved keyword on future versions of SQL Server. You might need to use with also like [DATA]
Consider to use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection connection = new SqlConnection(ConnectionString))
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = #"INSERT INTO [Data] (Name, [Sur-Name], Score, Avg)
VALUES (#Name, #SurName, #Score, #Avg)";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
}
You are trying to mix concatenated queries with parametrized. Always use parametrized queries, It will save you from SQL Injection.
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Data] (Name, [Sur-Name], Score,Avg) VALUES (
#Name, #SurName, #Score, #Avg)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
Also consider enclosing your connection and command object in using statement.
As #Soner has mentioned in his answer, use Square brackets for Data and Sur-Name

Insert data into SQL Server from C# code

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query

Using parameters inserting data into access database

I have the following method to inserting data into an an access databasewhich works fine but I do get a problem if I try to insert text that contains single quotes I have learned.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
From what I understand one of the ways to solve the problem is by using parameters. I am not sure how to do this to be honest. How could I change the above code so that I insert the data by using parameters instead?
Same as for any other query:
a) Replace actual hardcoded parameters in your OleDbCommand with placeholders (prefixed with #),
b) Add instances of OleDbParameter to the DbCommand.Parameters property. Parameter names must match placeholder names.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
using (OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.Jet.OleDb.4.0;"+
"Data Source="+Server.MapPath("App_Data\\BookRateInitial.mdb"));
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
// create command with placeholders
cmd.CommandText =
"INSERT INTO bookRated "+
"([title], [rating], [review], [frnISBN], [frnUserName]) "+
"VALUES(#title, #rating, #review, #isbn, #username)";
// add named parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#title", title),
new OleDbParameter("#rating", rating),
...
});
// execute
cmd.ExecuteNonQuery();
}
}
}
You have to use Parameter to insert Values. Its is allso a security Issue.
If you do it like that a sql injection could by made.
Try like this:
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
For Microsoft Access the parameters are positional based and not named, you should use ? as the placeholder symbol although the code would work if you used name parameters provided they are in the same order.
See the documentation for OleDbCommand.Parameters Property
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
Be sure to include the expected schema type where the parameter will be used AND the schema length if applicable.
I also recommend you always use using statements around your instances where the type implements IDisposable like the OleDbConnection so that the connection is always closed even if an exception is thrown in the code.
Changed Code:
var connectionStringHere = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb";
using (var conn = new OleDbConnection(connectionStringHere))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO bookRated ([title], [rating], [review], [frnISBN], [frnUserName]) VALUES(?, ?, ?, ?, ?)";
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) { Value = title});
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.Integer) { Value = rating });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 2000) { Value = review });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 60) { Value = ISBN });
cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 256) { Value = userName });
conn.Open();
var numberOfRowsInserted = cmd.ExecuteNonQuery();
}

Categories