Substring in insert command - c#

I have a field that is 50 caracters long so I need to do a sub-string but in insert command, but first I have to check if the value is to long and then sub-string this is the part of the code, I know it's not good, so how can this be done?
myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES(" + Lidoc_num + ",'" +
SEG_NUM + "','" +
drDOK["DOCTYP"] + "'," +
drDOK["HDRNUM"] + "," +
drDOK["WHNUM"] + "," +
drDOK["DOCNUM"] + ",'" +
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).Length > 50 ? Substring(0,50) + "')";

Of course, you should read carefully and adapt your code based on Jon Skeet's comment.
Beside that, you could write a small extension method
public static string ToShortenString(this string str, int maxLength) {
if (str == null) return null;//or string.Empty if you want to "hide" null values
return str.Substring(0, Math.Min(str.Length, maxLength));
}
then you could change your code to
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).ToShortenString(50) + "')";

SqlCommand command = new SqlCommand("INSERT INTO ERP_HEADER(#IDOC_NUM,#SEG_NUM,#DOCTYP,#HDRNUM,#WHNUM,#DOCNUM,#DOCNOT)", connection);
string DOCNOT = drDOK["DOCNOT"].ToString()
if(DOCNOT.Length > 50)
DOCNOT = DOCNOT.Substring(0,50);
command.Parameters.AddWithValue("#IDOC_NUM", Lidoc_num);
command.Parameters.AddWithValue("#SEG_NUM", SEG_NUM);
command.Parameters.AddWithValue("#DOCTYP", drDOK["DOCTYP"]);
command.Parameters.AddWithValue("#HDRNUM", drDOK["HDRNUM"]);
command.Parameters.AddWithValue("#WHNUM", drDOK["WHNUM"]);
command.Parameters.AddWithValue("#DOCNUM", drDOK["DOCNUM"]);
command.Parameters.AddWithValue("#DOCNOT", DOCNOT);
command.ExecuteNonQuery();
Never ever concatenate sql-strings, it's just like asking for trouble.

Use parameters to avoid SQL injection like Jon skeet already pointed out and avoid syntactic abomniations:
//assuming myQuery is of type SqlCommand
myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES( #Lidoc_num, #SEG_NUM, #DOCTYPHDRNUM, #WHNUM, #DOCNUM, #DOCNOT)";
myquery.CommandType = CommandType.Text;
myQuery.Parameters.AddWithValue("Lidoc_num", Lidoc_num);
//...other values
myQuery.Parameters.AddWithValue("DOCNUM", drDOK["DOCNUM"]);
string DOCNOT = drDOK["DOCNOT"].ToString();
//check for your string
if(DOCNOT.Length > 50)
DOCNOT = DOCNOT.Substring(0,50);
myQuery.Parameters.AddWithValue("DOCNOT", DOCNOT);

myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES(" + Lidoc_num + ",'" +
SEG_NUM + "','" +
drDOK["DOCTYP"] + "'," +
drDOK["HDRNUM"] + "," +
drDOK["WHNUM"] + "," +
drDOK["DOCNUM"] + ",'" +
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).Length > 50 ? drDOK["DOCNOT"].ToString().Substring(0,50) : drDOK["DOCNOT"].ToString() + "')";

Related

How to fix "Invalid Column Name" SQL Exception on MSSQL

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?

Errors when inserting date and time into QODBC query C#

I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.

ASP.net MVC: Input String Was Not In Correct Format

I'm trying to write to a database and am getting the "Input String Was Not In Correct Format" error. I'm assuming it's the data types on the last two columns but I'm not sure how to change. In SQL Server, they are both of the money datatype. Code below:
string query = null;
for (int i = 0; i < result.Tables[0].Rows.Count; i++)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
query = "INSERT INTO Upload(Email, TimeStamp, EmployeeId, Name, Title, Department, Race, Gender, AnnualizedBase, AnnualizedTCC) VALUES ('"
+ System.Web.HttpContext.Current.User.Identity.GetUserId() + "', "
+ " '" + DateTime.Now + "', "
+ " '" + result.Tables[0].Rows[i][0].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][1].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][2].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][3].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][4].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][5].ToString() + "', "
+ Convert.ToInt32(result.Tables[0].Rows[i][6]) + ", "
+ Convert.ToInt32(result.Tables[0].Rows[i][7])
+ ")";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
The error Input string was not in correct format is most likely caused by one of the values in your column not being convertible to an int. If the datatype in SQL is money then you should try and convert to a decimal and not an int. Try this for each row:
decimal num;
if (decimal.TryParse(result.Tables[0].Rows[i][6], out num))
{
// use num because it is indeed a decimal (money in SQL)
}
else
{
// What do you want to do? Log it and continue to next row?
}
Also please read Bobby Tales and example of paratmetrized query.

Insert button in C# and SQL Server

I'm trying to fix the code of an insert button. It's a button that inserts data into the database.
Here is my code :
private void button2_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
sqlCon.Open();
// string requete = "INSERT INTO [RECAP] VALUES ('" + textBox1.Text + "''" + textBox2.Text + "''" + comboBox2.SelectedValue + "''" + comboBox3.SelectedValue + "''" + textBox5.Text + "''" + textBox6.Text + "''" + Global.Global.GolbVar + "''" + DateTime.Now.ToShortDateString() + "');";
string requete = "INSERT INTO dbo.RECAP(code_reseau, tot_dcl, mont_debou, gch_dep, typ_port, mois, annee, emt_dep, utilisateur, date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";
cmd = new SqlCommand(requete, sqlCon);
cmd.ExecuteNonQuery();
MessageBox.Show("Ajouté !");
sqlCon.Close();
}
Every time I try to run this it generates an exception that says
Incorrect syntax near ','
Try replacing
string requete = "INSERT INTO dbo.RECAP(code_reseau,tot_dcl,mont_debou,gch_dep,typ_port,mois, annee, emt_dep,utilisateur,date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";
with
SqlCommand com = new SqlCommand("INSERT INTO RECAP (code_reseau, tot_dcl, mont_debou, gch_dep, typ_port,mois, annee, emt_dep, utilisateur, date_maj) VALUES(#txt1, #txt5, #txt6, ,#combo2, #combo3, 0, 0, 0, 0, 0)", sqlCon);
com.Parameters.AddWithValue("#txt1", textBox1.Text);
com.Parameters.AddWithValue("#txt5", textBox5.Text);
com.Parameters.AddWithValue("#txt6", textBox6.Text);
com.Parameters.AddWithValue("#combo2", comboBox2.SelectedValue);
com.Parameters.AddWithValue("#combo3", comboBox3.SelectedValue);
and see if that works
Check if the below
textBox5.Text
textBox6.Text
comboBox2.SelectedValue
comboBox3.SelectedValue
are all numeric type.
As they are not passed in single quotes, so either their values should be convertible to a number (and the respective column is also of that type) or they are causing the error as some text is inserted in the SQL statement without any quotes around it.

syntax error in query

I am new to programming and is developing a new desktop database applcation in Access, I am trying to insert data into a table. I had two datetime picker and I read the value from it as
jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;
and I had passed the databean to a function
public void addaction(JobCodeDataBean jobcodedatabean)
{
MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());
try
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
}
catch (Exception)
{
MessageBox.Show(e);
}
but i am getting the exception at the query
Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'.
In access the date fields are in short date format
Please somebody help to sort out my mistake
Incorrect quotations. To avoid these kinds of mistakes, use ordered parameters:
var myCommand = new OleDbCommand(
"INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);
myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);
Using parameters also helps protect against SQL injection attacks. In your example, if one of the strings contained an apostrophe, it would fail unless you correctly converted it to two apostrophes. With parameters these are escaped correctly automatically.
You forgot to enclose dates in quotes:
... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...
Note single quotes around both dates.

Categories