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..
Related
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.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
cn.ConnectionString = #"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
string n = Convert.ToString(txtfid.Text);
cmd.CommandText = "select * from Personal_det where FID=" + n + "";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
da1.SelectCommand = cmd;
da1.Fill(ds1, "Personal_det");
double dn = ds1.Tables["Personal_det"].Rows.Count;
if (dn == 0)
{
DateTime sdt = DateTime.Today;
SqlCommand cmd3 = new SqlCommand();
cn.Close();
cn.Open();
cmd3.CommandText = "insert into Personal_det(FID,Name,DOB,MobileNo,EmailId,add1,add2,add3,Pincode) values(#FID,#Name,#DOB,#MobileNo,#EmailId,#add1,#add2,#add3,#Pincode)";
cmd3.CommandType = CommandType.Text;
cmd3.Connection = cn;
cmd3.Parameters.Add("#FID", SqlDbType.VarChar,50);
cmd3.Parameters["#FID"].Value = this.txtfid.Text;
cmd3.Parameters.Add("#Name", SqlDbType.VarChar, 50);
cmd3.Parameters["#Name"].Value = this.txtname.Text;
cmd3.Parameters.Add("#DOB", SqlDbType.DateTime, 8);
cmd3.Parameters["#DOB"].Value = Convert.ToDateTime(this.txtdob.Text);
cmd3.Parameters.Add("#MobileNo", SqlDbType.Decimal, 18);
cmd3.Parameters["#MobileNo"].Value = this.txtmbl.Text;
cmd3.Parameters.Add("#EmailId", SqlDbType.VarChar, 50);
cmd3.Parameters["#EmailId"].Value = this.txtmail.Text;
cmd3.Parameters.Add("#add1", SqlDbType.VarChar, 50);
cmd3.Parameters["#add1"].Value = this.txtadd1.Text;
cmd3.Parameters.Add("#add2", SqlDbType.VarChar, 50);
cmd3.Parameters["#add2"].Value = this.txtadd2.Text;
cmd3.Parameters.Add("#add3", SqlDbType.VarChar, 50);
cmd3.Parameters["#add3"].Value = this.txtadd3.Text;
cmd3.Parameters.Add("#Pincode", SqlDbType.Decimal, 18);
cmd3.Parameters["#Pincode"].Value = this.txtpin.Text;
cmd3.ExecuteNonQuery();
cn.Close();
This is my C# code..Actually what i have done is previously i had FID as int now i converted it as varchar(50),because of some needs,i have already changed the datatype in sql..Personal_det is the table where in FID is a primary key constraint and foriegn key for other tables..Now When i am going to execute the code..it gives the error shown in the Image
Do not create CommandText using strings concatenation - such a bad practice make your sql queries vulnerable for sql-injections.
You can use SqlParameter also for "select" queries, like this.
cmd.CommandText = "select * from Personal_det where FID=#fid";
...
cmd.Parameters.Add(new SqlParameter("#fid", fidValue))
since FID is string you need to use '' as below
cmd.CommandText = "select * from Personal_det where FID='" + n + "'";
above will avoid your exception but it is not safe
You need to use parameters like you did on second case
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?
I'm trying to display the SQL query result in a label but it's not showing. This is my code:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
Need help please. Thanks!
Try this one.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
Is there a typo in there? You have two calls to the database:
showresult.ExecuteNonQuery();
This won't return a value and I'm not sure why you would have it there
string actresult = ((string)shresult.ExecuteScalar());
Unless you have a shresult variable, this query should error. What is the shresult variable?
Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=#ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("#ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("#ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = #id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
This will dispose the connection and has no string concatenation in the query.
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.