When I execute my code below, this error message occurs: [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
An exception of type 'System.Data.SqlClient.SqlException occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near 'in'. "
private void buttonSave_Click(object sender, EventArgs e)
{
string name = txtfullName.Text;
string fname = texfatherName.Text;
string gender = "";
bool isChecked = radioButton1Male.Checked;
if (isChecked)
{
gender = radioButton1Male.Text;
}
else
{
gender = radioButton2Female.Text;
}
string dob = dateTimePicker1DOB.Text;
Int64 mobile = Int64.Parse(texmobNo.Text);
string emai = textEmail.Text;
string semester = comboBoxSemester.Text;
string department = comboBox2Department.Text;
string schoo = textsch.Text;
string duration = comboBox3Duration.Text;
string address = richTextBoxAdress.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source =CR7\\SQLEXPRESS;database =coll;integrated security =True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Insert in to NewAdmission(fname,mname,gender,dob,mobile,email,semester,prog,sname,duration,addres)values('" + name + "','" + fname + "','" + gender + "','" + dob + "'," + mobile + ",'" + mobile + "','" + emai + "','" + semester + "','" + department + "','" + schoo + "','" + address + "')";
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet DS = new DataSet();
DA.Fill(DS);
con.Close();
MessageBox.Show("Data Saved. Remembet The Registration ID", "Data", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}

Your command text is incorrect. This line:
cmd.CommandText = "Insert in to NewAdmission(fname,mname,gender,dob,mobile,email,semester,prog,sname,duration,addres)values('" + name + "','" + fname + "','" + gender + "','" + dob + "'," + mobile + ",'" + mobile + "','" + emai + "','" + semester + "','" + department + "','" + schoo + "','" + address + "')";
The statement should be insert into rather than insert in to:
cmd.CommandText = "Insert into NewAdmission(fname,mname,gender,dob,mobile,email,semester,prog,sname,duration,addres)values('" + name + "','" + fname + "','" + gender + "','" + dob + "'," + mobile + ",'" + mobile + "','" + emai + "','" + semester + "','" + department + "','" + schoo + "','" + address + "')";
You should also try to avoid passing values into the sql statement in this way as SQL injection can be a problem. Should be passed as parameters into the statement

The correct SQL syntax is INSERT INTO not INSERT IN TO

Related

How to insert Persian words into a SQL Server database?

I am just wondering how to insert Persian characters into my service-based database?
When I save my data it shows something like '???'.
I have checked such questions like this. But, the solutions were not useful.
private void button1_Click(object sender, EventArgs e)
{
objConnection.Open();
if (ctypeCheckBox.Checked == true)
st = 1;
else if (ctypeCheckBox.Checked == false)
st = 0;
string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted!");
objConnection.Close();
}
Two things:
Never ever combine your query string with values
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
Should be immediately replaced with
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime)
VALUES(#cname, #cid, #ccredit, #csession, #st, #cstartDateDate, #cendDate, #cStartTime, #cEndTimeB)";
and then you should use
SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
for all parameters. This will save you from a lot of problems including SQL injection.
In the database your columns should have nvarchar data type.
Good luck
You should use SqlParameter .Giving example of only one parameter.You can add others as same way.
string query = "INSERT INTO LectureTable(Cname) VALUES(#name)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#name", cnameTextBox.Text);
param.SqlDbType = SqlDbType.String;
cmd.Parameters.Add(param);
.....
}

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]

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
}

Categories

Resources