Insert Data into database via mySQL using visual studio in C# - c#

So I'm trying to insert data into an SQL Database, which was created in Visual Studio 2017 via a Service-Based Database.
Here is the code
private void save() {
Book book = new Book();
book.Id = System.Convert.ToInt32(idtxtbox.Text);
book.title = titletxtbox.Text;
book.author = authortxtbox.Text;
string query = "INSERT INTO Book VALUES(" + System.Convert.ToInt32(idtxtbox.Text) + "," + titletxtbox.Text + "," + authortxtbox.Text + ")";
using (conn = new SqlConnection(connString))
using (SqlCommand command = new SqlCommand(query, conn)) {
conn.Open();
command.ExecuteNonQuery();// Error here
conn.Close();
}
clear();
}
If I enter data like
id = 001
title = "The Book"
Author = "Main Author"
I get an error that says " System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Book'.' ". What am I doing wrong, and how can I fix it?

Try to do it this way and thus avoid sql injections:
SqlConnection conexion;
private void save() {
conexion = cConexion.getConexion();
SqlCommand comand = new SqlCommand();
comand.Connection = conexion;
comand.CommandText = "INSERT INTO Book(Id, title, author) VALUES(#Id, #title, #author)";
comand.Parameters.Add("Id", SqlDbType.Int, 3).Value = this.idtxtbox.Text;
comand.Parameters.Add("title", SqlDbType.NChar).Value = this.titletxtbox.Text;
comand.Parameters.Add("author", SqlDbType.NChar).Value = this.authortxtbox.Text;
comand.ExecuteNonQuery();
clear();
}
I like to use a connection class to handle the connections
class cConexion
{
private static SqlConnection conexion;
public static SqlConnection getConexion()
{
if (conexion != null)
{
return conexion;
}
conexion = new SqlConnection(Properties.Settings.Default.MyConnectionString);
try
{
conexion.Open();
return conexion;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error" + e.Message);
return null;
}
}
public static void cerrarConexion()
{
if (conexion != null)
{
conexion.Close();
}
}
}

Related

propbem the mysqlconnection when using public variable in class level

I have c# class that make me to connect the database and make some operations on it.
#region Var
private readonly string DbPath;
public MySqlConnection DbConn;
#endregion
#region Constructor
public ClsDb()
{
DbPath = "SERVER= " + Db.Default.ServerName + "; " +
"DATABASE= " + Db.Default.DbName + "; " +
"UID= " + Db.Default.UserName + "; " +
"PWD= " + Db.Default.UserPass + "; " +
"PORT= " + Db.Default.ThePort+"; sslmode=none";
DbConn = new MySqlConnection(DbPath);
}
#endregion
as you see I declared (mysqlconnection) :
DbConn = new MySqlConnection(DbPath);
so after that I check the connection:
public bool CheckConn()
{
try
{
if (DbConn.State == ConnectionState.Open)
{
DbConn.Close();
}
if (DbConn.State == ConnectionState.Closed)
{
DbConn.Open();
return true;
}
return false;
}
catch
{
MessageBox.Show(Msgs.Default.ConnErr,
Settings.Default.ComName,
MessageBoxButtons.OK,
MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
return false;
}
}
and after that I'm trying to execute SQL statement by method:
public void RunSql(string xSql, MySqlParameter[] xPar)
{
//...
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
// ....
if (xPar != null)
{
xCmd.Parameters.AddRange(xPar);
}
//...
xCmd.ExecuteNonQuery();
}
but it gives me the following error:
"Connection must be valid and open."
when I checked the code by the breakpoints I got that everything is ok and it opens the connection very well but when it execute (public void RunSql) and exactly on the line:
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
when I tried to solve it I changed (public MySqlConnection DbConn) to (public Static MySqlConnection DbConn) and it worked but I needed to know why that happened although I declared the variable as public?? and why it worked when I changed to Static??
I'm using my own class for this. In it isn't necessary to close the connection because uses the 'using'.
The class:
Connection (return open connection)
public static MySqlConnection GetConn()
{
MySqlConnection conn = new MySqlConnection(ConnString);
try
{
conn.Open();
}
catch (MySqlException)
{
throw;
}
return conn;
}
Insert Commands (accept params)
public static int InsertSqlCommand(string db, params (string param, object value)[] listParams)
{
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
int linhasAfetadas = cmd.ExecuteNonQuery();
return linhasAfetadas;
}
}
}
Select Command (accept params)
public static DataTable SelectSqlCommand(string db, params (string param, object value)[] listParams)
{
DataTable dttoken = new DataTable();
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
using (MySqlDataAdapter sqlDA = new MySqlDataAdapter(cmd))
{
sqlDA.Fill(dttoken);
return dttoken;
}
}
}
}

i get the error MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax

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 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}

How to efficiently update a huge amount of data via code

I am working on updating a huge amount of data. About 200k of data in the particular table. But I find my code inefficient and slow. Is there a way to optimize this code and make it twice or thrice faster? I am trying to convert their existing password to hashed. I tried linq before but I encounter an "Execution Timeout" issue. Until now I can't find a solution to it. The code below was the one that I am currently using.
var hashedProvider = Membership.Providers["HashedProvider"];
if (hashedProvider != null)
{
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
{
con.Open();
string sql = "SELECT Email from aspnet_membership where IsLockedOut = '0'" +
" AND IsApproved = '1' And PasswordFormat != '1'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
var UserName = Reader["Email"].ToString();
MembershipUser user = Membership.GetUser(UserName);
if (user != null)
{
Guid userID = new Guid(user.ProviderUserKey.ToString());
string CurrentPassword = user.GetPassword();
try
{
UpdateUser(userID, 1);
var resetPassword = hashedProvider.ResetPassword(UserName, null);
bool Password_Changed = hashedProvider.ChangePassword(
UserName, resetPassword, CurrentPassword);
if (!Password_Changed)
{
UpdateUser(userID, 2);
}
}
catch (Exception e)
{
UpdateUser(userID, 2);
}
}
}
if (Reader != null)
Reader.Close();
}
}
Below is the code for UpdateUser() method.
public static void UpdateUser(Guid userID, int type)
{
for (Int32 attempt = 1; ;)
{
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
{
con.Open();
string Sql = "UPDATE [aspnet_Membership] SET [PasswordFormat] = #Type where" +
" UserID = #UserID";
SqlCommand cmd = new SqlCommand(Sql, con);
cmd.Parameters.AddWithValue("#UserID", userID);
cmd.Parameters.AddWithValue("#Type", type);
cmd.ExecuteNonQuery();
break;
}
}
}

How to Query Return Value on using Compact SQL Command?

I using a compact database created on visual studio. just for a stand alone system with it's database intact already although i'm stuck here in using a select query that could retrieve a boolean if the user exist on the database and also then return it's ID and Username if the user entry exist. can i ask for help regarding on this one.. I am a student trying to learn c# on using compact database.
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (!IsEmpty())
{
if (!IsLenght())
{
using (SqlCeConnection con = new SqlCeConnection("Data Source=" +
System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = (bool)cmd.ExecuteScalar();
con.Close();
MessageBox.Show(validlogin.ToString());
if (validlogin == true)
{
// cmd. return value ID
// cmd. return value Username
//SysMain Mn = new SysMain();
//Mn.ShowDialog();
//this.Hide();
}
}
}
}
}
catch (Exception ex)
{
gbf.msgBox(1, ex.Message.ToString(), "");
}
}
The code below is probably better, unless there is something special and unstated about the schema of LoginTB.
// ...
var validLogin = false;
using (SqlCeConnection con = new SqlCeConnection(
"Data Source=" +
System.IO.Path.Combine(
Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location),
"INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = ((int)cmd.ExecuteScalar()) > 0;
}
MessageBox.Show(validlogin.ToString());
// ...
Note the use of COUNT

C# SQL Server CE - Update won't work

I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.

Categories

Resources