How can I execute multiple SQL commands using c# - c#

I was trying to use this code two run two commands in one connection, which I couldn't do, here is my code:
using (SqlConnection connection = new SqlConnection(""))
{
string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";
using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader reader = RetriveCommand.ExecuteReader();
while (reader.Read())
{
string coluna = reader.GetString(reader.GetOrdinal("quatro"));
string coluna1 = reader.GetString(reader.GetOrdinal("tres"));
Boolean ElementDisplayed;
try
{
}
catch (NoSuchElementException i)
{
ElementDisplayed = false;
GDataPicker();
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
{
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
}
}
}
}
}
conn.Close();
}
}
My problem is most likely in the lines where I do:
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
And says i already have one datareader.
Help would be really appreciated, thanks in advance!

Append you second command in "query2". As it is inline query Sql will consider that as two different query (Append after semicolon) and will execute in the same connection

Related

Why is my Ajax data not sending through to my SQL Server

I am trying to get my data from a web page to a server without requiring a page refresh. The js brings in the data; however, it (the data) does not reach my db, I am new to ajax and not sure if I am doing this correctly
JS:
function insert() {
let batchid = document.getElementById("batchID").value;
let batchname = document.getElementById("batchName").value;
let totenum = document.getElementById("toteNum").value;
let flower = document.getElementById("flowers").value;
let trim = document.getElementById("trim").value;
let wastemat = document.getElementById("wasteMaterial").value;
let empint = document.getElementById("empInital").value;
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insert.cshtml?bid=" + batchid + "&bn" + batchname + "&tn" + totenum + "&fl" + flower + "&tr=" + trim + "&wm" + wastemat + "&ei" + empint , false);
xmlhttp.send(null);
alert(" Record inserted successfully");
}
C#:
SqlConnection con = new SqlConnection(Server);
string batchID, batchName, toteNum, flowers, trim, wasteMaterial, empInital;
public void OnGet()
{
batchID = Request.Query["bid"].ToString();
batchName = Request.Query["bn"].ToString();
toteNum = Request.Query["tn"].ToString();
flowers = Request.Query["fl"].ToString();
trim = Request.Query["tr"].ToString();
wasteMaterial = Request.Query["wm"].ToString();
empInital = Request.Query["ei"].ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO HarvestedCannabis VALUES ('" + batchID.ToString() + "', '" + batchName.ToString() + "', " +
"'" + toteNum.ToString() + "', '" + flowers.ToString() + "', " +
"'" + trim.ToString() + "', '" + wasteMaterial.ToString() + "', " +
"'" + empInital.ToString() + "')";
cmd.ExecuteNonQuery();
con.Close();
The data is not being added to my db and I am not sure what I'm missing

how to save imported excel in datagridview to database C#

how to save imported data from excel in datagridview to database in C#
I have saved records and exported to excel sheet, it exported along with data ID, now I have re-imported back to datagridview from excel. now I want to save data to database.
Important to know:
Database name "Records.sdf" using SQL Compact 3.5
DataGridViewName is RecordsDataGridView.
I'm using following code but it's not working.
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
ERROR RECEIVING
Column Name not Valid, column name = Cash
Try this query string
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ",'"+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ",'" + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + "')";
You should pass varchar field enclosed with single quote.
var str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values("
+ RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '"
+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "',"
+ RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + ","
+ "'" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "'" + ","
+ RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + ","
+ "'" + dataGridView1.Rows[index].Cells[8].Value.ToString() + "'" + ")";
There are a few ways to do this.
Here is one method.
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
You can do this as well.
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
Something like this will work too.
private void buttonSave_Click_1(object sender, EventArgs e) // save to invoice
{
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "INSERT INTO invoice (p_code, p_name, p_category, p_price) " +
VALUES (#code, #name, #category, #price)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in MyTable.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#code", row["p_code"]);
sc.Parameters.AddWithValue("#name", row["p_name"]);
sc.Parameters.AddWithValue("#category", row["p_category"]);
sc.Parameters.AddWithValue("#price", row["p_price"]);
sc.ExecuteNonQuery();
}
con.Close();
}

Updating Database

So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();
You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";
Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.
Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.
In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.

Why my query return null

I want to ask why query return null and not update what i want. Sorry I'm still new with asp.net and c#
myquery = "UPDATE kenderaan SET buatan = " + "'" + carmake + "'" + "," +
"model = " + "'" + carmodel + "'" + "," +
"no_enjin = " + "'" + carenjin + "'" + "," +
"cc = " + carcc + "," +
"seatCapacity = " + carseat + "," +
"tahunBuatan = " + caryear + " WHERE no_kenderaan = " + "'" + carid + "'" + "," +
"AND ic = " + "'" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
restructure your code into this, use Connection object, Command Object, using statement.
string myquery = "UPDATE kenderaan SET buatan = #carmake ," +
" model = #carmodel ," +
" no_enjin = #carenjin ," +
" cc = #carcc ," +
" seatCapacity = #carseat ," +
" tahunBuatan = #caryear " +
"WHERE no_kenderaan = #carid " +
" AND ic = #cusid ";
using (MySqlConnection _conn = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = myquery;
_comm.CommandType = CommandType.Text;
_comm.Parameters.AddWithValue("#carmake",carmake);
_comm.Parameters.AddWithValue("#carmodel",carmodel);
_comm.Parameters.AddWithValue("#carenjin",carenjin);
_comm.Parameters.AddWithValue("#carcc",carcc);
_comm.Parameters.AddWithValue("#carseat",carseat);
_comm.Parameters.AddWithValue("#caryear",caryear);
_comm.Parameters.AddWithValue("#carid",carid);
_comm.Parameters.AddWithValue("#cusid",cusid);
try
{
_conn.Open();
_comm.ExecuteNonQuery();
MessageBox.Show("Updated!");
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString()); // as mentioned on the comment
}
}
}
Reasons why you need to parameterized your query:
avoids SQL Injection
makes your code more readable
etc.. :D
Sources
AddWithValue
Add (recommended and leaving you this as an assignment :D)
Create a DbCommand to execute the Update statement by using ExecuteNonQuery() method. If you are using SQL Server then you can use this piece of code snippet:
using System.Data.SqlClient;
string query = "UPDATE kenderaan SET buatan = #carmake" +
", model = #carmodel" +
", no_enjin = #carenjin" +
", cc = #carcc" +
", seatCapacity = #carseat" +
", tahunBuatan = #caryear" +
" WHERE no_kenderaan = #carid AND ic = #cusid";
using (SqlConnection conn = new SqlConnection("<connection string>"))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#carmake", carmake);
cmd.Parameters.AddWithValue("#carmodel", carmodel);
cmd.Parameters.AddWithValue("#carenjin", carenjin);
cmd.Parameters.AddWithValue("#carcc", carcc);
cmd.Parameters.AddWithValue("#carseat", carseat);
cmd.Parameters.AddWithValue("#caryear", caryear);
cmd.Parameters.AddWithValue("#carid", carid);
cmd.Parameters.AddWithValue("#cusid", cusid);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try this code in place of your code:
and make sure that varchar parameters are compare to string values.
string myquery = "UPDATE kenderaan SET buatan = '" + carmake + "',model = '"+
carmodel + "',no_enjin = '" +carenjin + "',cc = " + carcc + ",seatCapacity = " +
carseat + ",tahunBuatan = " + caryear +
" WHERE no_kenderaan = '" + carid + "' AND ic = '" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
UPDATED: Apologize, I had just corrected your query with your where condition I just removed comma which you used to separate two condition.
To avoid SQL Injection Attacks, Use one of these :
1) Parameters with Stored Procedures
2) Use Parameters with Dynamic SQL
3) Constrain Input
you can find more information over HERE

SQL c# updating table

I am doing this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where JobID=" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
JobID is a uniqueidentifier
And I am getting this error:
Conversion failed when converting from a character string to uniqueidentifier.
What am I doing wrong?
The JobID field looks like this:
DB9424E5-1E73-4108-A855-B252E516A2A2
2EB17B8B-C0A1-46FE-82AF-37AEF2A8A6EC
C24F0460-7667-4A3A-8D8F-64B9728C2359
8DCDB020-8C7B-493E-9D21-719CBAFC16B6
This will be more secure (safe from SQL-injection), easer to read and understand, and faster because prepared statements get their execution plan cached. If you have different sql, it can't use a cached execution plan.
SqlCommand cmd =
new SqlCommand(
#"update FileLog set FaxStatus=#fs, FaxedPageCount=#ct, #dtFaxed=#dt, ......., where JobID=#id")
{CommandType = CommandType.Text};
cmd.Prepare();
cmd.Connection = connection;
cmd.Parameters["#id"].Value = row.ItemArray[0];
...
i found the solution. turns out you need to do this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"BiscomCode=" + "'" + row.ItemArray[5].ToString() + "', " +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
you have to convert it to a varchar first
It's very likely one of your job ids is not a valid Guid.
Here's a method to check for guid:
public static bool IsGuid(string input)
{
Regex isGuid = new Regex(#"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
try
{
return isGuid.IsMatch(input);
}
catch
{
return false;
}
}
So before issuing the query command do a check on the jobid. If it doesn't match, escape it and log it to revisit later.

Categories

Resources