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.
Related
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
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
I have a table in mysql for users. Sometime user has a boss and sometime it don't.
So boss data type in nullable int(it is a foreign key, that's why nullable INT).
I was using following code and it was causing problem when boss value is null, producing following error "Incorrect integer value: '' for column 'boss_id' at row 1"
string query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myreader;
try
{
conDataBase.Open();
myreader = cmdDataBase.ExecuteReader();
conDataBase.Close();
return true;
}
catch (Exception ex)
{
conDataBase.Close();
MessageBox.Show(ex.Message);
return false;
}
So, i changed the code for string query as follow:
string query = "";
if(systemuser.Boss!=null)
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
else
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
It worked because, Mysql by default put null at the skipped values.
Now according to my scenario, I have to update boss_id from int to null and sometime from null to int. But my query always skip if value is null. Can you please help me in changing the insert statement in such a way that it would insert null value in boos(if its null) and don't just skip it.
Firstly, you should use parameters, it gives you a clean code and avoid injection.
You can use parameters like this:
string query = string.Format("INSERT INTO {0}.system_user (`boss_id`, `name`, `user_name`, `password_2`, `designation`, `digital_signature`, `functional_role`, `group_2`)" +
"VALUES (#boss_id, #name, #user_name, #password_2, #designation, #digital_signature, #functional_role, #group_2)", databasename);
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#boss_id", systemuser.Boss ?? (object)DBNull.Value);
cmdDataBase.Parameters.AddWithValue("#name", systemuser.Name);
cmdDataBase.Parameters.AddWithValue("#user_name", systemuser.UserName);
cmdDataBase.Parameters.AddWithValue("#password_2", systemuser.Password);
cmdDataBase.Parameters.AddWithValue("#designation", systemuser.Designation);
cmdDataBase.Parameters.AddWithValue("#digital_signature", systemuser.DigitalSignature);
cmdDataBase.Parameters.AddWithValue("#functional_role", systemuser.FunctionalRole);
cmdDataBase.Parameters.AddWithValue("#group_2", systemuser.Group);
Note "#boss_id", systemuser.Boss ?? (object)DBNull.Value, this is because you can not use null directly in the parameters.
UPDATE:
If you want to update or delete you can use parameters too:
You can write your queries like this:
string query = string.Format("UPDATE {0}.system_user SET `name` = #name WHERE `boss_id` = #boss_id", databasename);
or
string query = string.Format("DELETE FROM {0}.system_user WHERE `boss_id` = #boss_id", databasename);
For datetime columns you can see this question. It has very good answers.
You are encapsulating the value of Systemuser.Boss in single quotes, doesn't this indicate that you are trying to insert a string into an integer column?
string query = #"INSERT INTO {0}.system_user (
`boss_id`,
`name`,
`user_name`,
`password_2`,
`designation`,
`digital_signature`,
`functional_role`,
`group_2`)
VALUES
{1},
'{2}',
'{3}',
'{4}',
'{5}',
'{6}',
'{7}',
'{8}')
";
string formattedQuery = string.Format(query,
databasename, // {0}
Systemuser.Boss, // {1}
Systemuser.Name, // {2}
etc, etc);
EDIT: missed a part where you said 'when it was null'... you need to use:
(Systemuser.Boss ?? "NULL")
I am new to C# and SQL. Now from a form I access a function in a class.
My code is
public void updateSupplierInformation(string id, string name, string balance, string place, string address, string phone, string bankname, string bankbranch, string accountno)
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlCommand NewCmd = conn.CreateCommand();
NewCmd.Connection = conn;
NewCmd.CommandType = CommandType.Text;
NewCmd.CommandText = " update supplier set " + " ID = " + "'" + id + "'" + " , NAME = " + "'" + name + "'" + " , BALANCE = " + "'" + balance + "'" + " , PLACE = " + "'" + place + "'" + " , LOCATION = " + "'" + address + "'" + ", PHONE = " + "'" + phone + "'" + " , BANK_NAME = " + "'" + bankname + "'" + " , BANK_BRANCH = " + "'" + bankbranch + "'" + ", ACCOUNT_NO = " + "'" + accountno + "'" + " where ID = " + "#id";
NewCmd.Parameters.AddWithValue("#id",id);
NewCmd.ExecuteNonQuery();
conn.Close();
}
Now if a record doesn't exist in the database with the given id the application stops immediately. How can I handle this? I want to show a message that the data entered is wrong and ask the user to enter another data
ExecuteNonQuery() returns number of rows affected by an INSERT, UPDATE or DELETE statement.If you need to check sql exception you have to include a try catch statement in your function.
public void updateSupplierInformation(string id, string name, string balance, string place, string address, string phone, string bankname, string bankbranch, string accountno)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlCommand NewCmd = conn.CreateCommand();
NewCmd.Connection = conn;
NewCmd.CommandType = CommandType.Text;
NewCmd.CommandText = " update supplier set " + " ID = " + "'" + id + "'" + " , NAME = " + "'" + name + "'" + " , BALANCE = " + "'" + balance + "'" + " , PLACE = " + "'" + place + "'" + " , LOCATION = " + "'" + address + "'" + ", PHONE = " + "'" + phone + "'" + " , BANK_NAME = " + "'" + bankname + "'" + " , BANK_BRANCH = " + "'" + bankbranch + "'" + ", ACCOUNT_NO = " + "'" + accountno + "'" + " where ID = " + "#id";
NewCmd.Parameters.AddWithValue("#id",id);
int a=NewCmd.ExecuteNonQuery();
conn.Close();
if(a==0)
//Not updated.
else
//Updated.
}
catch(Exception ex)
{
// Not updated
}
}
ExecuteNonQuery returns the number of rows affected - if it's 0, that means there were no matching rows to update. Of course, that's only if the update actually "works" in terms of not throwing an exception... whereas I suspect it's throwing an exception in your case, which probably isn't to do with the row not existing in the database. (It's possible that there's some code you haven't shown which does depend on the row existing, mind you.)
Additionally:
You should use parameterized SQL for all parameters rather than including the values directly in your SQL.
You should use using statements to dispose of resources reliably.
It looks like you're using a single connection - don't do that. Create (and dispose via using) a new connection each time you want to perform a database operation, and let the connection pool handle the efficiency
Work out why the application is just stopping. An exception is almost certainly being thrown, and it's really important that when that happens, you get the details of the exception. You may want to catch it and keep going (at some high level) depending on the exact context... but you should always at least end up logging it.
My guess (on a casual inspection) is that the problem is that your update statement tries to update the ID, which would presumably be read-only. But you'll find that out when you fix your exception handling.
Simply check the condition
int a=NewCmd.ExecuteNonQuery();
if(a==0)
//Not updated.
else
//Updated.
ExecuteNonQuery() -> This function return integer value.
Thank you
I know that there is already an answer posted but let`s try something else:
SqlConnection SQLConn = new SqlConnection("datahere");
SqlCommand SQLComm = new SqlCommand();
SQLcomm.Connection = SQLConn;
SQLConn.Open();
SQLComm.CommandText = "SQL statement goes here"
SqlDataReader dataReader = SQLComm.ExecuteReader();
dataReader.Read();
if(dataReader.HasRows == true){ //if it has rows do code
//do code
}
else{
// do other code
}
HasRows will return a bool value
let sql = UPDATE TABLE SET column = '${data}' WHERE column = "value
db.query(sql, (err, result)=> {
console.log(result.affectedRows);
if(err) {
console.log(err);
return res.send({
message: "Error occured. please retry",
});
} else if(result.affectedRows != 0) {
console.log(result)
return res.send({
success:true,
message: "updated!"
});
}else if(result.affectedRows == 0) {
console.log(result)
return res.send({
success:false,
message: "not updated!"
});
} else {
console.log(result)
}
})
//this is a nodejs code
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