Related
I don't understand where the problem is, I try to fix, to search and I can't find the problem.
Incorrect syntax near ','.
Code:
using System.Data.SqlClient;
SqlConnection ABC = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand comm = new SqlCommand();
SqlDataReader dataRead;
private void B1_Click(object sender, EventArgs e)
{
ABC.Open();
comm.CommandText = "insert into dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura)values('"
+ C1.Text + "','" + T1.Text + "','" + T2.Text + "','" + C2.Text + "','" + DTP1.Value.ToString("MM/dd/yyyy") + "','" + T3.Text + "','" + T4.Text + "','" + T5.Text + "','" + T6.Text + "','" + T7.Text + "','"
+ T8.Text + "','" + T9.Text + "','" + T10.Text + "','" + T11.Text + "','" + T12.Text + "','" + T13.Text + "','" + T14.Text + "','" + T15.Text + "','" + DTP2.Value.ToString("MM/dd/yyyy") + "','" + T16.Text + "','" + T17.Text + "','" + T18.Text + "','" + C3.Text + "','" + C4.Text + "','" + C5.Text + "','" + T19.Text + "','" + T20.Text + "','" + C6.Text + "','" + T21.Text + "','" + T22.Text + "','" + T23.Text + "','" + T24.Text + "','" + DTP3.Value.ToString("MM/dd/yyyy") + "','" + C7.Text + "','" + T25.Text
+ "','" + T26.Text + "','" + T27.Text + "','" + T28.Text + "','" + T29.Text + "','" + C8.Text + "','" + T30.Text + "','" + C9.Text + "','" + DTP4.Value.ToString("MM/dd/yyyy") + "','" + C10.Text + "','" + T31.Text + "','" + T32.Text + "','" + T33.Text + "','" + DTP5.Value.ToString("MM/dd/yyyy") + "','" + T34.Text + "','" + T35.Text + "','" + T36.Text + "')";
comm.ExecuteNonQuery();
ABC.Close();
MessageBox.Show("Adaugat cu succes!");
}
You have two commas successively. Remove the same.
Suggestion: Please use parameterized queries.
As already pointed out the Exception is caused by a double , in your statement. Really you need to use Sql Parameters. Also use the using statement, and do not share connection instances (again, see the link).
// store this in the app.config instead of hard coding
const string SqlConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30";
private void B1_Click(object sender, EventArgs e)
{
const string sqlText = "INSERT INTO dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura) VALUES (#facultate,#domeniul,#specializare,#forma_invatamant,#d_inscriere,#nume_prenume,#cod,#localitate,#judet,#tara,#strada,#numar,#bloc,#scara,#etaj,#apartament,#sector,#cod_p,#data_nasterii,#locul_nasterii,#judet_n,#tara_n,#sex,#starea_civila,#cetatenie,#cetatenie_op,#etnie,#cnp,#serie,#numar_cnp,#eliberat,#e_data,#studii_preuni,#nume_unitate,#spec_fili_profil,#oras_s,#judet_s,#tara_s,#forma_de_invatamant,#medie_bac,#durata_studii,#data_absolvirii,#tipul_diploma,#seria_diploma,#numarul_diploma,#emis_de_catre,#data_emiterii,#nr_foi_matricole,#introducere_date,#semnatura)";
// use using statements to ensure connections are closed and resources are freed
using(var con = new SqlConnection(SqlConnectionString))
using(var comm = new SqlCommand(sqlText, con))
{
comm.Parameters.Add(new SqlParameter("#facultate", SqlDbType.VarChar){Value = C1.Text});
comm.Parameters.Add(new SqlParameter("#domeniul", SqlDbType.VarChar){Value = T1.Text});
// etc, fill this in with the remaining parameters
con.Open();
comm.ExecuteNonQuery();
// not really a great place for this, I recommend splitting the ADO.NET code from the UI code
MessageBox.Show("Adaugat cu succes!");
}
}
Finally understand what Exceptions are and how to read them.
this is right query try it
using System.Data.SqlClient;
SqlConnection ABC = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand comm = new SqlCommand();
SqlDataReader dataRead;
private void B1_Click(object sender, EventArgs e)
{
ABC.Open();
comm.CommandText = "insert into dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura)values('"
+ C1.Text + "','" + T1.Text + "','" + T2.Text + "','" + C2.Text + "','" + DTP1.Value.ToString("MM/dd/yyyy") + "','" + T3.Text + "','" + T4.Text + "','" + T5.Text + "','" + T6.Text + "','" + T7.Text + "','"
+ T8.Text + "','" + T9.Text + "','" + T10.Text + "','" + T11.Text + "','" + T12.Text + "','" + T13.Text + "','" + T14.Text + "','" + T15.Text + "','" + DTP2.Value.ToString("MM/dd/yyyy") + "','" + T16.Text + "','" + T17.Text + "','" + T18.Text + "','" + C3.Text + "','" + C4.Text + "','" + C5.Text + "','" + T19.Text + "','" + T20.Text + "','" + C6.Text + "','" + T21.Text + "','" + T22.Text + "','" + T23.Text + "','" + T24.Text + "','" + DTP3.Value.ToString("MM/dd/yyyy") + "','" + C7.Text + "','" + T25.Text
+ "','" + T26.Text + "','" + T27.Text + "','" + T28.Text + "','" + T29.Text + "','" + C8.Text + "','" + T30.Text + "','" + C9.Text + "','" + DTP4.Value.ToString("MM/dd/yyyy") + "','" + C10.Text + "','" + T31.Text + "','" + T32.Text + "','" + T33.Text + "','" + DTP5.Value.ToString("MM/dd/yyyy") + "','" + T34.Text + "','" + T35.Text + "','" + T36.Text + "')";
comm.ExecuteNonQuery();
ABC.Close();
MessageBox.Show("Adaugat cu succes!");
}
Also try to use parameterized queries.
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]
I got the excel value in gridview and now I need to insert all the values in rows to sql server 2008.
When i try to iterate throught Gridview rows it throws the error in for loop near the dg_AgentSFR.Rows as "DataGrid' does not contain a definition for 'Rows' "
Here is my code:
protected void savedatafromgv()
{
foreach (GridViewRow g1 in ***dg_AgentSFR.Rows)***
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
Please help me to resolve this.
Thanks in advance.
Datagrid does not contain a definition for rows. Instead of rows, it has items.
use this
foreach (DataGridItem Dr in dg_AgentSFR.items)
DataGrid Class
And also use parameterized query to avoid How does SQLParameter prevent SQL Injection
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER....) values (#POL,#POD,#FORWARDER)
try this code
if(dg_AgentSFR.Rows.Count>0)
{
foreach (GridViewRow g1 in dg_AgentSFR.Rows)
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
A datagrid in ASP.NET does indeed not contain a property Rows. The GridView on the other hand, does contain a property Rows. More info:
DataGrid class
GridView class
I suggest you use the GridView, this is kind of the successor of the DataGrid. And another important tip: use SQL parameters and not just a string-query (SQL injection).
Make sure you use GridViewRowEventArgs and NOT GridViewCommandEventArgs
protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Your code here
}
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);
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.. ;)