SQL server remove space before value when I insert data - c#

When I insert data using a SqlCommand, It also add space before values which I just inserted. How do I avoid adding spaces?
Here is the insert query code:
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract]
([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person],[Contact_No],FileName,FileData,FileType)
VALUES (' " + TextBox1.Text + "',' " + TextBox2.Text + "',' " + TextBox3.Text + "',' " + TextBox4.Text + "',' " + TextBox5.Text + "',' " + DepartmentTextBox.SelectedValue.ToString() + "',' " + TextBox7.Text + "',' " + TextBox8.Text + "',' " + TextBox9.Text + "',' " + TextBox10.Text + "',' " + TextBox11.Text + "',#Name,#Data,#Type)", con);

Of course any kind of problems surface when you use string concatenation to build command text. In your case you have inadvertently added a space before your control values.
If you had used a parameterized query this problem would not have arisen
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] " +
"([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept]," +
"[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person]," +
"[Contact_No],FileName,FileData,FileType) VALUES (" +
"#cid, #name, #desc, #cby, #vname, #rdept, #stdate, #expdate, " +
"#tc, #cp, #cno, #file, #fdate, #ftype",con)
SqlParameter p = new SqlParameter("#cid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text));
cmd.Parameters.Add(p);
.... and so on for the other parameters required
By the way, remember that if you have an IDENTITY column you should not try to insert anything in that column (Contract_ID is particulary suspect here)

It's inserting spaces because you have extra spaces in your query string. I changed "',' " to "','":
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] ([Contract_Id],
[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],
[Expiration_Date],[TypeofContract],[Contact_Person], Contact_No],FileName,FileData,FileType)
VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" +
TextBox4.Text + "','" + TextBox5.Text + "','" + DepartmentTextBox.SelectedValue.ToString()
+ "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" +
TextBox10.Text + "','" + TextBox11.Text + "',#Name,#Data,#Type)", con);

Related

Column count doesn't match value count at row 1 when try to save into db

Im tring to save data on mysql db but i always get "Column count doesn't match value count at row 1"
I tried to recode this sql command, seen some videos about this but cant found nothing that work
string Insert =
"INSERT INTO db.pcs(Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "," + marca + "," + user + "," + ram + ","
+ cpu + "," + disco + "," + tiposo + "," + so + ","
+ lice + "," + tipopc + "," + progs + "')";
using (MySqlConnection cn = new MySqlConnection(connst))
{
cn.Open();
MySqlCommand cmd = new MySqlCommand(Insert, cn);
try
{
if (cmd.ExecuteNonQuery() == 1)
{
pb1.Visible = true;
timer1.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Its supose to add to db but on the try messagebox i get "Column count doesn't match value count at row 1"
I think you should make " ' " for each value
string Insert =
"INSERT INTO db.pcs (Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "','" + marca + "','" + user + "','" + ram + "','"
+ cpu + "','" + disco + "','" + tiposo + "','" + so + "','"
+ lice + "','" + tipopc + "','" + progs + "')";
You set only one quote at the start and one at the end.
So it is only one value you set into your insert command.
Try this or use sqlparams:
string Insert =
"INSERT INTO db.pcs(Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "', '" + marca + "', '" + user + "', '" + ram + "', '"
+ cpu + "', '" + disco + "', '" + tiposo + "', '" + so + "', '"
+ lice + "', '" + tipopc + "', '" + progs + "')";

SQL Command Error

here is the story :
Im trying to insert some data form the form to my data base but some thing wrong with the syntax "Vs Say so" but i can't find the mistake and some one help ?
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
conn.Open();
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
INSERT INTO invoice companyName, ... missing opening brace, correct is
INSERT INTO invoice(column1, column2, ...) VALUES (#Columns1, #columns2, ...)
Coming to point 2: you're open for sql-injection. Use parameterized queries.
Change your
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
To
string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (#name,#rate,#vatno,#tinno,#adline1,#adline2,#city)";
command.Parameters.AddWithValue("name",txtname.Text);
command.Parameters.AddWithValue("rate",txtrate.Text);
....
*Edit: For more info, google "c# parameterized sql"
You put Wrong bracket
INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');

c# mysqlcommnand insert into mysql database

i have a program that insert a list of field into the database. When i use my own computer to insert the datetime field it looks completing fine. however, when i insert it using a windows 7 chinese edition, the field become 0000-00-00 00:00:00
this is the command
MySqlCommand myCommand4 = new MySqlCommand("Insert into OrderRecords_table values('" + OrderIDLabel.Text + "','" + customerCode + "','" + customer + "','" + TelComboBox.Text + "','" + LicenseComboBox.Text + "','" +
DriverComboBox.Text + "','" + AddressComboBox.Text + "','" + LocationTypeComboBox.Text + "','" + PickupComboBox.Text + "','" + CustomerTypeLabel.Text + "','" +
Convert.ToDecimal(TotalPriceLabel.Text) + "','" + status + "','" + note + "','" + sandReceiptNo + "','" + createtiming + "','" + Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "')", myConnection);
myCommand4.ExecuteNonQuery();
i know it looks a bit messy, but the part where it says
STR_TO_DATE('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','%Y/%M/%d /%H/%m/%s'))"
is the part where i insert the current datetime. it works just fine when i use english version of windows, but whenever i use chinese edition, it isnert 0000-00-00 00:00:00 instead of the actual time, i have tried to change the format for showing dates in control panel, but it is still having the same problem.
anyone knows what the problem would be ?
Thanks
edited my code
var sql = "insert into OrderRecords_table values(#OrderID, #customercode, #customer, #PhoneNumber, #license, #driver, #address, #type, #pickupLocation, #PaymentMethod, #totalPrice, #status, #notes, #sandreceiptNo,#createTime, #EditTime)";
using (var myCommand4 = new MySqlCommand(sql, myConnection))
{
myCommand4.Parameters.AddWithValue("#orderId", MySqlDbType.VarChar).Value = OrderIDLabel.Text;
myCommand4.Parameters.AddWithValue("#customercode", MySqlDbType.VarChar).Value = customerCode;
myCommand4.Parameters.AddWithValue("#customer",MySqlDbType.VarChar).Value = customer;
myCommand4.Parameters.AddWithValue("#PhoneNumber", MySqlDbType.VarChar).Value =TelComboBox.Text;
myCommand4.Parameters.AddWithValue("#license", MySqlDbType.VarChar).Value = LicenseComboBox.Text;
myCommand4.Parameters.AddWithValue("#driver", MySqlDbType.VarChar).Value = DriverComboBox.Text;
myCommand4.Parameters.AddWithValue("#address", MySqlDbType.VarChar).Value = AddressComboBox.Text;
myCommand4.Parameters.AddWithValue("#Type", MySqlDbType.VarChar).Value = LocationTypeComboBox.Text;
myCommand4.Parameters.AddWithValue("#pickupLocation", MySqlDbType.VarChar).Value = PickupComboBox.Text;
myCommand4.Parameters.AddWithValue("#PaymentMethod", MySqlDbType.VarChar).Value = CustomerTypeLabel.Text;
myCommand4.Parameters.AddWithValue("#totalPrice", MySqlDbType.Decimal).Value = Convert.ToDecimal(TotalPriceLabel.Text);
myCommand4.Parameters.AddWithValue("#status", MySqlDbType.VarChar).Value = status;
myCommand4.Parameters.AddWithValue("#notes", MySqlDbType.VarChar).Value =status;
myCommand4.Parameters.AddWithValue("#sandreceiptNo", MySqlDbType.VarChar).Value = sandReceiptNo;
myCommand4.Parameters.AddWithValue("#createTiming", MySqlDbType.DateTime).Value = createtiming;
myCommand4.Parameters.AddWithValue("#EditTime", MySqlDbType.DateTime).Value = DateTime.Now;
myCommand4.ExecuteNonQuery();
its saying that i have some invalid input, but i have checked a few times that all the fields are asigned to the correct type.. . don't know what is happening
I've rewritten your code to a more standardized implementation (with best practices). Note that I've pulled your query out into a separate variable to let the code and query become more readable.
var sql = "insert into orderrecords_table values " +
"(#orderId, " +
" #customercode, " +
" #customer, " +
" #telephone, " +
" #license, " +
" #driver, " +
" #address " +
" #locationType, " +
" #pickup, " +
" #customerType, " +
" #totalPrice, " +
" #status, " +
" #note, " +
" #sandreceiptNo, " +
" #createTiming, " +
" #currentTime) ";
using (var myCommand4 = new MySqlComm## Heading ##and(sql, connection))
{
myCommand4.Parameters.AddWithValue("#orderId", OrderIDLabel.Text) ;
myCommand4.Parameters.AddWithValue("#customercode", customerCode);
myCommand4.Parameters.AddWithValue("#customer", customer);
myCommand4.Parameters.AddWithValue("#telephone", TelComboBox.Text);
myCommand4.Parameters.AddWithValue("#license", LicenseComboBox.Text);
myCommand4.Parameters.AddWithValue("#driver", DriverComboBox.Text);
myCommand4.Parameters.AddWithValue("#address", AddressComboBox.Text);
myCommand4.Parameters.AddWithValue("#locationType", LocationTypeComboBox.Text);
myCommand4.Parameters.AddWithValue("#pickup", PickupComboBox.Text);
myCommand4.Parameters.AddWithValue("#customerType", CustomerTypeLabel.Text);
myCommand4.Parameters.AddWithValue("#totalPrice", Convert.ToDecimal(TotalPriceLabel.Text));
myCommand4.Parameters.AddWithValue("#status", status);
myCommand4.Parameters.AddWithValue("#note", status);
myCommand4.Parameters.AddWithValue("#sandreceiptNo", sandReceiptNo);
myCommand4.Parameters.AddWithValue("#createTiming", createtiming);
myCommand4.Parameters.AddWithValue("#currentTime", DateTime.Now);
myCommand4.ExecuteNonQuery();
}
MySqlCommand Insert = new MySqlCommand("INSERT INTO [TABLE] ([Date], [TEXT]) VALUES(#Date, #Text) ", myConnection);
Insert.CommandTimeout = 60; //if you need
Insert.Parameters.AddWithValue("#Date", DateTime.Now);
Insert.Parameters.AddWithValue("#Text", "Hello word!");
Insert.ExecuteNonQuery();
Insert.Dispose();

Syntax error in INSERT INTO statement OleDBCOmmand

I have an issue when trying to insert Rows from Datatable into an Excel sheet. I keep getting syntax error but when i insert the sql string into mssql server there is no issue verifying the sql statement.
this is my code:
public void InsertData(DataTable kpiData)
{
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\KPIReports\";
string fileName = #"\Return_Report - " + DateTime.Today.ToShortDateString() + ".xlsx";
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
File.Delete(file);
}
File.Copy(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\ReportTemp.xlsx", folderPath + fileName);
System.Data.OleDb.OleDbConnection connection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + folderPath + fileName + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=YES;\"");
connection.Open();
myCommand.Connection = connection;
foreach (DataRow row in kpiData.Rows)
{
string weight = row[11].ToString().Replace(',', '.');
sql = "Insert into [Data$] (WeekNr, AccountNumber, Barcode, Barcode2, PickupDate, DeliveryCustID, DeliveryAlias, PickupCustID, PickupAlias, DeliveryAttentionName, Coli, Weight, Note, DeliveryType, " +
"Name, Street, HouseNo, Postal, City, DanxCode, Receiver, PODTime, OnTime, [Service]) Values('" + row[0].ToString() + "','" + row[1].ToString() + "','" + row[2].ToString() + "','" + row[3].ToString() + "','" + row[4].ToString() + "','"
+ row[5].ToString() + "','" + row[6].ToString() + "','" + row[7].ToString() + "','" + row[8].ToString() + "','" + row[9].ToString() + "','" + row[10].ToString() + "','" + weight + "','" + row[12].ToString() + "','" + row[13].ToString() + "','"
+ row[14].ToString() + "','" + row[15].ToString() + "','" + row[16].ToString() + "','" + row[17].ToString() + "','" + row[18].ToString() + "','" + row[19].ToString() + "','" + row[20].ToString() + "','" + row[21].ToString() + "','" + row[22].ToString() + "','" + row[23].ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
}
myCommand.Dispose();
connection.Close();
releaseObject(myCommand);
releaseObject(connection);
}
and this is the sql string:
Insert into [Data$] (WeekNr, AccountNumber, Barcode, Barcode2, PickupDate, DeliveryCustID, DeliveryAlias, PickupCustID, PickupAlias, DeliveryAttentionName, Coli, Weight, Note, DeliveryType, Name, Street, HouseNo, Postal, City, DanxCode, Receiver, PODTime, OnTime, [Service]) Values('20','44730629311','12626707007','0681739685','10-05-2014 15:22:13','xxxxx','xxxx','xxxxx','Asker','','1','0.2','','N','xxx','xxxx','111','0665','xxx','xxx','xxxx','13-05-2014 07:00:00','OT','Reverse')
I cant seem to find the problem. I hope someone cant help me..
thanks in advance.
I have found the issue.
The problem was that i didnt have the Note column in brackets. Because Note is a reserved word then it has to have brackets around it like so: [Note]

ADO.NET objects in C# not working properly

SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\CustomersDB.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Customers (ID, Date, GUIA, SName, SAddress, SCity, SState, SZipCode, SPhone, SEmail, RName, RAddress, RCity, RState, RZipCode, RPhone, REmail) VALUES (1,'"+textBox1.Text + "','" + textBox2.Text+"','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox16.Text + "','" + textBox15.Text + "','" + textBox14.Text + "','" + textBox13.Text + "','" + textBox12.Text + "','" + textBox11.Text + "','" + textBox10.Text +"')" , con);
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added successfully!");
As you can see, I'm trying to add some data to the database, created inside a C# Windows Forms application.
However, after executing the code, I receive no error, but when I look at the table data, nothing has changed.
In other words, no data is being added, even though the code is executed correctly.
What's the flaw here? Any help is appreciated.
Firstly, I would like to point out that you have one giant SQL-injection sitting there. Secondly, take a look at Rows not being updated to see if it is the same issue you are facing.
The main flaw is the whole User Instance and AttachDbFileName= approach. Visual Studio will be copying around the .mdf file and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. CustomersDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=CustomersDB;Integrated Security=True
and everything else is exactly the same as before...
1 Your query will create the SQL Injection, try to use SP or LINQ for more secure execution.
[2] First of all try to execute your long query return string value with your sql server database table because here you not show your table structure so that any single quote will not execute the proper query.
string sqlstr = "INSERT INTO Customers (ID, Date, GUIA, SName, SAddress, SCity, SState, SZipCode, SPhone, SEmail, RName, RAddress, RCity, RState, RZipCode, RPhone, REmail) VALUES (1,'"+textBox1.Text + "','" + textBox2.Text+"','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox16.Text + "','" + textBox15.Text + "','" + textBox14.Text + "','" + textBox13.Text + "','" + textBox12.Text + "','" + textBox11.Text + "','" + textBox10.Text +"')"
[3] Last point better naming is important for coding.
cn.ConnectionString = #"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\CustomersDB.mdf;Integrated Security=True;User Instance=True";
cn.Open();
SqlCommand com = new SqlCommand();
com.Connection = cn;
com.CommandType = CommandType.Text;
com.CommandText = "INSERT INTO Customers (ID, Date, GUIA, SName, SAddress, SCity, SState, SZipCode, SPhone, SEmail, RName, RAddress, RCity, RState, RZipCode, RPhone, REmail) VALUES (1,'"+textBox1.Text + "','" + textBox2.Text+"','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox16.Text + "','" + textBox15.Text + "','" + textBox14.Text + "','" + textBox13.Text + "','" + textBox12.Text + "','" + textBox11.Text + "','" + textBox10.Text +"')" ;
com.ExecuteNonQuery();
MessageBox.Show("Saving is done!");
Try this Code and See wheather its working or not i think this should work.. ;)

Categories

Resources