Error on Looping mssql statment using c# windows form - c#

I am trying to check whether database have the following data before making decision to update or insert but current i have a problem not able to loop through as it only execute once.
//It is suppose to loop based on the value in account.devices.Count --> last tried with 10 values
for (int z = 0; z < account.devices.Count; ) have 10 data inside account.device.Count
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
myReader.Close();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
z++;
}
Thanks in advance
Update working codes
try
{
for (int z = 0; z < account.devices.Count; )
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
myReader.Close();
z++;
}
}
catch(Exception e)
{
this.listBox1.BeginInvoke((MethodInvoker)delegate()
{
listBox1.Items.Add(DateTime.Now.ToString("hh:mm:ss tt") + " [DB Insert] " + e.ToString());
this.listBox1.SelectedIndex = listBox1.Items.Count - 1;
this.listBox1.SelectedIndex = -1;
});
}

Related

problems entering data into mysql

i have this code that is being used to enter data into mysql, but I have found an error that says:
"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 ''11/05/2018)' at line 1'"
private void Button_Click(object sender, RoutedEventArgs e)
{
string especie = txt1.Text;
string nombre = txt2.Text;
string fechanac = txt3.Text;
string fecharev = txt4.Text;
int numanimales = 0;
int cont = 0;
var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "animalia";
if (dbCon.IsConnect())
{
string query = "SELECT COUNT(*) FROM ANIMALES;";
var cmd = new MySqlCommand(query, dbCon.Connection);
numanimales = Convert.ToInt32(cmd.ExecuteScalar());
}
int id = numanimales + 1;
if (dbCon.IsConnect())
{
if (especie == "" || nombre == "" || fechanac == "" || fecharev == "")
{
MessageBox.Show("Introduzca todos los datos");
}
else
{
cont = 1;
MySqlDataReader reader;
string query = "INSERT INTO ANIMALES VALUES (" + id + ",FALSE,'" + especie + "','" + nombre + "','" + fechanac + "','" + fecharev + "');";
var cmd = new MySqlCommand(query, dbCon.Connection);
reader = cmd.ExecuteReader();
MessageBox.Show("Animal añadido");
reader.Close();
}
if (cont == 1)
{
this.Close();
}
}
}
}
The error appears in this part of the code
MySqlDataReader reader;
string query = "INSERT INTO ANIMALES VALUES (" + id + ",FALSE,'" + especie + "','" + nombre + "','" + fechanac + "','" + fecharev + ");";
var cmd = new MySqlCommand(query, dbCon.Connection);
reader = cmd.ExecuteReader();
MessageBox.Show("Animal añadido");
reader.Close();
Thank you very much in advance to those of you who can help me.
You are missing closing quotation marks on the last attribute:
...,'" + fecharev + ");";
should be
...,'" + fecharev + "');";

Connection was not closed. The connection's current state is open

How to fix this problem? I don't know why this error occur when I already add Clode().
The error will go here:
public void existType()
{
try
{
con.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, con);
da.Fill(ds, "tblRoomType");
int counter = 0;
string tabletype = "tblRoomType";
if (counter < ds.Tables[tabletype].Rows.Count)
{
string type = ds.Tables[tabletype].Rows[counter]["Type"].ToString();
if (type == txtRoomType.Text)
{
editRoomType(); //There will be no error if I remove this and include the MessageBox below.
MessageBox.Show("Successfully Edited", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("This " + txtRoomType.Text + " is already exist.", "EXIST", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else //Remove this will remove the error
{
addRoomType();
MessageBox.Show("Successfully Added", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//to here
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This are the code of editRoomType() and addRoomType():
public void addRoomType()
{
con.Open();
string addtypequery = "INSERT INTO tblRoomType VALUES ('" + this.typeid + "','" + txtRoomType.Text + "','" + txtRoomRate.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "','" + txtMaxOcc.Text + "')";
cmd = new OleDbCommand(addtypequery, con);
cmd.ExecuteNonQuery();
con.Close();
loadRoomType();
txtRoomType.ReadOnly = false;
txtRoomType.Enabled = false;
txtRoomRate.Enabled = false;
txtMaxOcc.Enabled = false;
txtExtraCharge.Enabled = false;
txtCancelFee.Enabled = false;
btnAddRoomType.Enabled = false;
txtRoomType.Clear();
txtRoomRate.Clear();
txtMaxOcc.Clear();
txtExtraCharge.Clear();
txtCancelFee.Clear();
}
public void editRoomType()
{
con.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, con);
cmd.ExecuteNonQuery();
con.Close();
}
The existType() will be go here:
private void btnAddRoomType_Click(object sender, EventArgs e)
{
if (txtRoomType.Text != "" || txtRoomRate.Text != "" || txtExtraCharge.Text != "" || txtCancelFee.Text != "" || txtMaxOcc.Text != "")
{
existType();
}
else
{
MessageBox.Show("Please fill in the space provided","OOPPSS!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The error is because you call con.Open in existType, then you either call addRoomType or editRoomType, both of which call con.Open again before you call con.Close in existType. Calling con.Open on an already open connection will throw the error you are seeing.
You can either remove the calls to con.Open/con.Close inside of the addRoomType or editRoomType and only call them in existType, or use local connections for each method, like so:
public void existType()
{
try
{
using (var conn = new SqlConnection())
{
conn.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, conn);
da.Fill(ds, "tblRoomType");
}
//rest of code
}
}
public void editRoomType()
{
using (var conn = new SqlConnection())
{
conn.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, conn);
cmd.ExecuteNonQuery();
}
}
Note that you don't have to call Close since the using statement will do that for you.
Try like this -
try
{
con.Open();
.......
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Open();
}
}

Possible solution for locking the table in sqlserver using asp.net

I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.

Updating Database on button click

i have a button that suppose to update data into the database.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
conn.Close();
}
but i get this error..
can someone help?
update =
i've changed my code to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
but the problem now is that , there's no update.
the iCount in the database is an INT , value is 0.
There is also no update for the viewtime and lastview.
where did i go wrong now?
change this:
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
you dont need the "'" apostrophe around it becuase its a number. That would definitely get you string not in correct format error
I would guess maybe the icount value is not a number, i would recommend using TryParse just in case. And that should keep this error from happening. What to do about a bad value getting returned by the query is another issue.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = 0;
if(Int32.TryParse(x,out y))
{
System.Diagnostics.Debug.WriteLine("iCount was an valid int32");
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
}
else
System.Diagnostics.Debug.WriteLine("iCount was NOT a valid int32, value: " + x);
conn.Close();
}
Have you checked the value of the 'x' variable? The exception informs that the value of X isn't a valid integer, so the FormatException is thrown.

How to handle a syntax error in an Access INSERT statement and a .NET DataGridView control?

I'm working with Access (.accdb), and a Windows Forms application, written in C#.
I get this error when I'm trying to insert data into a database table.
System.Data.OleDb.OleDbException:Sintax error in INSERT INTO statement.
adaptador.InsertCommand.ExecuteNonQuery();
I have tried to go through the direct route and update method but coming up with the same error!
My code:
private void btnCronograma_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=mydatabase.accdb");
string sql;
int idProyecto, idMes, meta, real;
OleDbDataAdapter adaptador = new OleDbDataAdapter();
//for (int i = 0; i < this.dataGridView8.Rows.Count - 1; i++)
//{
foreach (DataGridViewRow row in dataGridView8.Rows)
{
DataGridViewComboBoxCell combo3 = row.Cells["idProyecto"] as DataGridViewComboBoxCell;
DataGridViewComboBoxCell combo4 = row.Cells["idMes"] as DataGridViewComboBoxCell;
MessageBox.Show(combo3.Value.ToString());
MessageBox.Show(combo4.Value.ToString());
idProyecto = int.Parse(combo3.Value.ToString());
idMes = int.Parse(combo4.Value.ToString());
meta = int.Parse(dataGridView8.Rows[0].Cells[3].Value.ToString());
real = int.Parse(dataGridView8.Rows[0].Cells[4].Value.ToString());
MessageBox.Show(meta.ToString());
MessageBox.Show(real.ToString());
//for (int i = 0; i < this.dataGridView8.Rows.Count - 1; i++)
//{
sql = "INSERT INTO IndicadorProyecto (idProyecto, idMes, meta, real) VALUES('" + idProyecto + "' , '" +
idMes + "' , '" + meta + "' , '" + real + "') ";
//sql = "INSERT INTO IndicadorProyecto (idMes, meta, real) VALUES('" + idMes + "' , '" + meta + "' , '" + real + "') ";
if (combo3 == null)
{
MessageBox.Show("No se pudo convertir");
}
else if (combo4 == null)
{
MessageBox.Show("No se pudo convertir");
}
else
{
}
try
{
conn.Open();
adaptador.InsertCommand = new OleDbCommand(sql, conn);
adaptador.InsertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
//}
}
}
You should not concatenate strings into SQL statements.
By doing so, you break your code and create a SQL injection vulnerability.
Instead, you should use parameters.
For example:
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=mydatabase.accdb"))
using (var command = new OleDbCommand(#"INSERT INTO IndicadorProyecto (idProyecto, idMes, meta, real) VALUES(?, ?, ?, ?") {
command.Parameters.AddWithValue("a", idProyecto);
command.Parameters.AddWithValue("b", idMes);
command.Parameters.AddWithValue("c", meta);
command.Parameters.AddWithValue("d", real);
conn.Open();
command.ExecuteNonQuery();
}

Categories