ADO.NET objects in C# not working properly - c#

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.. ;)

Related

C# windowsform - Getting Syntax Error at Insert into statement

I'm trying to remake my system and my older system is 100% working, but when I changed something (I added a lot of columns in ms access database) I did the correct format in inserting data of each textboxes but it still says "error in insert into statement".
This is my code. Please take your time reading the query for that is only the error I got. I double checked the spelling or capitalization on each field from database as well as here.
try
{
connection.Open(); //open connection
OleDbCommand command = new OleDbCommand(); // command object , we can execute to validate our database
command.Connection = connection; // make a connection for the command
command.CommandText = " insert into StudentsRecord([StudentID],Name,Section,Semester,MathPrelim,MathMidterm,MathFinals,MathAverage,MathFinalGrade,EnglishPrelim,EnglishMidterm,EnglishFinals,EnglishAverage,EnglishFinalGrade,SciencePrelim,ScienceMidterm,ScienceFinals,ScienceAverage,ScienceFinalGrade,StatisticsPrelim,StatisticsMidterm,StatisticsFinals,StatisticsAverage,StatisticsFinalGrade,ReadandWritePrelim,ReadandWriteMidterm,ReadandWriteFinals,ReadandWriteAverage,ReadandWriteFinalGrade) values ('" + txtStudentID.Text + "' , '" + txtName.Text + "' , '" + txtSection.Text + "' , '" + cmbSemester.SelectedItem + "', '" + txtMathp.Text + "' , '" + txtMathm.Text + "' , '" + txtMathf.Text + "' , '" + txtMatha.Text + "' , '" + txtMathFG.Text + "' , '" + txtEnglishp.Text + "' , '" + txtEnglishm.Text + "', '" + txtEnglishf.Text + "','" + txtEnglisha.Text + "','" + txtEnglishFG.Text + "','" + txtMathFG.Text + "','" + txtSciencep.Text + "','" +txtSciencem.Text+ "','" + txtSciencef.Text + "','" + txtSciencea.Text + "','" + txtScienceFG.Text + "','" + txtStatisticsp.Text + "','" + txtStatisticsm.Text + "','" + txtStatisticsf.Text + "','" + txtStatisticsa.Text + "','" + txtStatisticsFG.Text + "','" + txtReadandWritep.Text + "','" + txtReadandWritem.Text + "','" + txtReadandWritef.Text + "','" + txtReadandWritea.Text + "','" + txtReadandWriteFG.Text + "')";
/* this is a string or a query used to execute. asterisk is used
to give you all column data from your database ,declaration of query */
command.ExecuteNonQuery(); // this is used to inserting data , updating or deleting data , this command will execute the above query
MessageBox.Show(" Saved! ");
}
catch (Exception a)
{
MessageBox.Show(" Error " + a.Message);
}
connection.Close();
I see in the first part you have 29 fields, but the inserted fields are 30...
In addition, you should use parameterized queries to avoid sql injection.
You need to debug codes and paste your CommandText to SSMS(SQL Sever Management Studio) to figure out errors.
Other suggestions:
command.CommandText = string.format("insert into StudentsRecord(..) VALUES(#...)); sql params to avoid sql injection
using(SqlConnection conn = ...)
Already solved the problem just now by putting [ ] on each field. which will be something like this:
insert into StudentsRecord(
[StudentID],[Name],[Section],[Semester],
[MathPrelim],[MathMidterm],[MathFinals]
) values ('"++"'..) ... etc.
Thanks everyone who tried to help me, have a good day!

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 + "');

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]

System.Web.UI.WebControls.DataGrid' does not contain a definition for 'Rows'

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
}

SQL server remove space before value when I insert data

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);

Categories

Resources