Error in asp.net c# code (mysql database connection) - c#

My code is to update a record if it already exists in database else insert as a new record.
My code is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
MyConnection.Open();
String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("", TextBox3.Text);
using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
MyCmd1.ExecuteNonQuery();
}
else
{
// set the SQL string
String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
"VALUES (?,?,?)";
// Create the Command and set its properties
OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
objCmd.Parameters.AddWithValue("", HiddenField4.Value);
objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
objCmd.Parameters.AddWithValue("", TextBox3.Text);
// execute the command
objCmd.ExecuteNonQuery();
}
}
}
I am getting the error as:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]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 'order,orderdate) VALUES ('04050040272009',' &' at line 1
The datatype for fields in table temp_save are:
fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
Please help me to resolve my error.

order is a reserved word. For a complete list of Reserved Words, please review this document.
You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)
INSERT INTO temp_save (fil_no,`order`,orderdate)....

i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql
String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";

Related

Don't know how to add up values in database

I have got the input to work but now I need to add to the original number every time I input to the database but I do not know how to do that, any help would be appreciated :)
String myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/coursework/Databases/runner database.accdb;"; // location of the database
OleDbConnection myConnection = new OleDbConnection(myConnectionString); // To create the database connection
OleDbCommand myCommand = new OleDbCommand(); // Use the connection for the command
myCommand.Connection = myConnection;
try
{
myConnection.Open(); // Opens the database connection
string query = "insert into tblTrainingInformation ([Username],[Calories Burnt]) values('"+GlobalUsername.username+"','" + this.txtCaloriesBurntRun.Text + "')";
OleDbCommand createCommand = new OleDbCommand(query, myConnection);
createCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to UPDATE an existing record adding a new value to your field or INSERT a new record if it is not present you need to know if your database already contains the Username.
So you need to run a SELECT query before and then decide if you need an UPDATE or an INSERT
(Access doesn't have some kind of UPSERT statement like MySql or Sql Server)
String myConnectionString = ".....";
string querySel = #"SELECT [Username],[Calories Burnt]
FROM tblTrainingInformation
WHERE [Username] = #uname";
using(OleDbConnection myConnection = new OleDbConnection(myConnectionString))
using(OleDbCommand myCommand = new OleDbCommand(querySel, myConnection))
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
using(OleDbDataReader reader = myCommand.ExecuteReader())
{
int calories = 0;
string query = "";
if(reader.Read())
{
// The record exists, read the calories and add the new value
// then execute the UPDATE
calories = Convert.ToInt32(reader["Calories Burnt"]);
calories += Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"UPDATE tblTrainingInformation
SET [Calories Burnt] = #cal
WHERE [Username] = #uname";
}
else
{
// Record doesn't exist, INSERT the new data
calories = Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"INSERT INTO tblTrainingInformation
([Calories Burnt],[Username])
VALUES(#cal, #uname)";
}
reader.Close();
myCommand.Parameters.Clear();
myCommand.Parameters.AddWithValue("#cal", calories);
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
myCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
}
}
I have made a couple of assumption here.
First I assume that UserName is the primary key in this table so you can retrieve the record using the WHERE on username value.
The second assumption is the type of the field Calories Burnt.
It should be a numeric field and, to simplify the example, I have considered it to be an integer.
These assumptions should be checked and fixed if they are not true.
Said that, notice the use of the Using Statement to correctly dispose the connection, command and reader. The removing of string concatenation from your queries is another important point. You should ALWAYS use the parameter collection to avoid Sql Injection (albeit improbable with Access) and error in parsing your values.
A final note on the order of the parameters. OleDb wants the parameter in the exact order in which the parameter placeholders appear in the query text so I have reversed the order of the INSERT to be compatible with the UPDATE command

C# MySql.Data INSERT INTO error

I use the MySql.Data in c# for a mysql connection. On another program it worked but currently i'm hanging on the INSERT INTO command.
I get the following error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: 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 'key) VALUES ('PGJWZBPOWTRPUTKY')' at line 1
With this code:
MySqlCommand Command = Connection.CreateCommand();
MySqlDataReader Reader;
Command.CommandText = "INSERT INTO jt_teamsync (key) VALUES ('" + TeamSyncKey + "')";
Connection.Open();
Reader = Command.ExecuteReader();
Connection.Close();
Thanks for any help
KEY is a reserved keyword in mysql. It should be escaped using backtick,
INSERT INTO jt_teamsync (`key`) VALUES(...)
MySQL Reserved Keywords List
As a sidenote, your query is very weak. It is vulnerable with SQL Injection. Parameterized the value to avoid from it, eg
string content = TeamSyncKey;
string connStr = "connection string here";
string sqlStatement = "INSERT INTO jt_teamsync (`key`) VALUES (#key)";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
using(MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#key", content);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(MySqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}

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

How to connect to a mysql database in C# and mimic the SELECT, UPDATE and INSERT functions

How can I connect to a MySQL database in C#, and use it to UPDATE values in the database, INSERT values in the database and SELECT values from the database.
Also, is it possible to get the value of the row, and mimic this PHP in C#?
$query = mysql_query("SELECT * FROM foo WHERE foo = 'foo');
while($row = mysql_fetch_assoc($query)) {
$foo1 = $row['foo1'];
//and so on
}
You have to download the MySql Connector/.NET.
How to connect to MySQL 5.0 using c# and mysql connector/net! lists some sample code which is quite similar to what you have:
private void button1_Click(object sender, System.EventArgs e)
{
string MyConString = "SERVER=localhost;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
}
First of all you have to learn about ADO.NET provider classes - They are responsible to establish a database session, execute commands (queries) and retrieve the results) and after that you have to download the MySql Connector API (Data Provider API) and learn the Provider class of mysql connector.
Connector/NET Examples
1- add References to my project : MySql.Data.MySqlClient
2- install the MySQL for Visual Studio download link :
https://dev.mysql.com/downloads/windows/visualstudio/
note: to create database Mysql free go to the link:
https://www.freesqldatabase.com/
the code :
string stconnetionString = "Server=Server name; Port=port number;
Database= DB name; Uid=User namw; Pwd=password;";
MySqlConnection conn = new MySqlConnection(stconnetionString);
try
{
conn.Open();
MySqlCommand mycmd = conn.CreateCommand();
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = "insert into Student(columes name) values(.....)";
mycmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved", "Window Application ", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
catch (Exception)
{
throw;
}

display information from sql db to asp.net webpage

I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.
What I need is to display a field from sql db table to my webpage like this example:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
How should I do that ?
I already have table members.
I need to do this with c# , I am using Visual Studio Web Express 2010
First step is add the SQL Client namespace:
using System.Data.SqlClient;
DB Connection
Then we create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Categories