Run time error while trying to insert data - c#

I'm traying to insert data into my microsoft database but this run time error is thrown
"Incorrect syntax near 'date'.\r\nMust declare the scalar variable \"#\"."
in this line Cmd.ExecuteNonQuery();
here is my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
//Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold[i];
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}
}
what should i do?

for the parameter names, you don't need to wrap with [] you can just use #Date, #AmountSold, #UnitPrice, #TotalPrice. Just make sure you fix them in both the statement and the parameter lists

Related

OleDb Update database.mdb

When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.

The first entry of DataTable fills the whole access database

I have read an excel file to a DataTable but only the first row fills the whole MS Access database. I have confirmed that the data in the DataTable and in the Excel file are the same. My code is shown below:
using (OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + outFilePath + ";Extended Properties=dBase IV"))
{
OleDbCommand cmd = new OleDbCommand();
string line = "001";
for (int n = 0; n < dt.Rows.Count; ++n)
{
if (String.IsNullOrEmpty(dt.Rows[n].Field<string>(0))) break;
cmd.CommandText = "INSERT INTO " + FileName +
"([JNL],[LINE],[TYPE],[DRACC],[CRACC],[EXPDRACC],[EXPCRACC]," +
"[DOCDATE],[REF],[DRAMT],[CRAMT]) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
string inacc = dt.Rows[n].Field<string>(0);
string justNumbers = new String(inacc.Where(Char.IsDigit).ToArray());
string acc = String.Format("{0:##-######-#}", justNumbers);
string jnl = JNL;
string Ref = REF;
string type = TYPE;
int dramt = 0;
int cramt = 0;
if (type == "50") dramt = Convert.ToInt32(100 * dt.Rows[n].Field < double>(2));
else cramt = Convert.ToInt32(100 * dt.Rows[n].Field < double>(2));
cmd.Parameters.Add("#JNL", OleDbType.VarChar).Value = jnl;
cmd.Parameters.Add("#LINE", OleDbType.VarChar).Value = line;
cmd.Parameters.Add("#TYPE", OleDbType.VarChar).Value = type;
cmd.Parameters.Add("#DRACC", OleDbType.VarChar).Value = justNumbers;
cmd.Parameters.Add("#CRACC", OleDbType.VarChar).Value = justNumbers;
cmd.Parameters.Add("#EXPDRACC", OleDbType.VarChar).Value = acc;
cmd.Parameters.Add("#EXPCRACC", OleDbType.VarChar).Value = acc;
cmd.Parameters.Add("#DOCDATE", OleDbType.Date).Value = DateTime.Now;
cmd.Parameters.Add("#REF", OleDbType.VarChar).Value = Ref;
cmd.Parameters.Add("#DRAMT", OleDbType.Integer).Value = dramt;
cmd.Parameters.Add("#CRAMT", OleDbType.Integer).Value = cramt;
cmd.CommandType = CommandType.Text;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
How to resolve this kind of issue?
You have to remove the parameters from your command. You are adding ever more parameters to it. Use
cmd.Parameters.Clear();
as first line of your for statement.
You add the first set of parameters and reuse the same command without clearing them, so you end up with a command that has n*11 (parameters defined/loop).
The first match in the collection is used to substitute your commands params so you get n Entries with same data.

CSV File import to SQL Server error

I am working for CSV File import to SQL Server
I got code from Internet ..working fine But when I am adding one extra field (User_Id) with that CSV file to SQL then this is giving error ....I am not able to understand where is doing mistake ....code...
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("Name");
tblReadCSV.Columns.Add("Email");
tblReadCSV.Columns.Add("Mobile");
tblReadCSV.Columns.Add("User_id");
string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Email/UploadFile/" + path));
path = Server.MapPath("~/Email/UploadFile/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
string strCon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile," + UserId +")";
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50, "Name");
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 50, "Email");
cmd.Parameters.Add("#Mobile", SqlDbType.VarChar, 50, "Mobile");
cmd.Parameters.Add("#User_id", SqlDbType.Int , UserId);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
Label1.Text = "File successfully uploaded";
You don't say what the error message is, nor where it occurs, but it seems to me that this line
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile," + UserId +")";
should probably be like this
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(#Name,#Email,#Mobile,#User_id)";
Replace
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id)
values(#Name,#Email,#Mobile," + UserId +")";
with
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id )
values(#Name,#Email,#Mobile,#UserId)";
In the above line, you are just declaring the parameters .
And this is how you actually pass the current user id:
cmd.Parameters.Add("#User_id", SqlDbType.Int , UserId);
Try this; hope it will work.
values(#Name,#Email,#Mobile," + UserId +")"// source from ur c
avoid ''+ UserId +'' in your string strSql..

C# How can i update some column datetime in datagridview to database

i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.

writing to sql server from C#, no errors returned

I am trying to write to a database from c#:
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.ConnectionString = "Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True";
// This creates an object with which you can execute sql
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = #"INSERT INTO [SalesDWH].[dbo].[PendingSpecimens]
([Date Entered]
,[Specimen ID]
,[Test]
,[Agency])
VALUES (#DateEntered,#SpecimenID,#Test,#Agency)";
command.CommandType = CommandType.Text;
// This is how you add a parameter to your sql command
// This way you are protected against SQL injection attacks
SqlParameter DateEntered = command.CreateParameter();
DateEntered.ParameterName = "#DateEntered";
DateEntered.Value = fields[0];
command.Parameters.Add(DateEntered);
SqlParameter SpecimenID = command.CreateParameter();
SpecimenID.ParameterName = "#SpecimenID";
SpecimenID.Value = fields[1];
command.Parameters.Add(SpecimenID);
SqlParameter Test = command.CreateParameter();
Test.ParameterName = "#Test";
Test.Value = fields[2];
command.Parameters.Add(Test);
SqlParameter Agency = command.CreateParameter();
Agency.ParameterName = "#Agency";
Agency.Value = fields[4];
command.Parameters.Add(Agency);
connection.Open();
int someint=command.ExecuteNonQuery();
}
}
catch(Exception ee)
{
textBox1.Text = ee.ToString();
}
In addition to no errors being returned, it has not written anything either!
What am I doing wrong?
I suspect that this line:
command.ExecuteNonQuery();
is not working.
Mut I do not understand why
please help!
Try this:
using (SqlConnection connection = new SqlConnection("Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True"))
{
string queryString = "INSERT INTO SalesDWH.dbo.PendingSpecimens([Date Entered], [Specimen ID], Test, Agency) VALUES (" + fields[0] + ", " + fields[1] + ", " + fields[2] + ", " + fields[4] + ")";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Maybe you are missing the parentheses in the values clause?

Categories

Resources