I am trying to connect to access 2010 database using the following string connection. But, it wont make any changes in the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:\\Program Files\\LogEntry\\LogEntry.accdb; Persist Security Info = False;");
conn.Open();
String text2send = "INSERT INTO TLC(Name,Department,Position,VisitDate,InTime,OutTime,Purpose,HelpedBy,Campus,HelpCode) VALUES(" + name + "," + department + "," + position + "," + date + "," + hourIn + "," + hourOut + "," + purpose + "," + helpedBy + "," + campus + "," + helpcode + ");";
OleDbCommand cmd = new OleDbCommand(text2send,conn);
conn.Close();
Edit:
This is the edited code that I used with Parameter query.
String name = nameTextbox.Text;
String department = departmentCBox.Text;
String purpose = purposeTextbox.Text;
String position = positionCBox.Text;
String date = inDate.Value.ToString("MM/dd/yyyy");
String helpCode = helpCodeCBox.Text;
String hourOut = ""+OutHour.Text+":"+OutMin+" "+OutMeredian;
String helpedBy= "";
String campus= "";
String helpcode= "";
String hourIn = "" + DateTime.Now.ToString("hh") + ":" +
DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt");
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:\\Program Files\\LogEntry\\LogEntry.accdb; Persist Security Info = False;");
conn.Open();
String text2send = "Insert Into TLC([Name],[Department],[Position],[VisitDate],[InTime],[OutTime],[Purpose],[HelpedBy],[Campus],[HelpCode]) VALUE(?,?,?,?,?,?,?,?,?,?);";
OleDbCommand cmd = new OleDbCommand(text2send,conn);
cmd.Parameters.AddWithValue("Name", name);
cmd.Parameters.AddWithValue("Department", department);
cmd.Parameters.AddWithValue("Position", position);
cmd.Parameters.AddWithValue("Purpose", purpose);
cmd.Parameters.AddWithValue("HelpedBy", helpedBy);
cmd.Parameters.AddWithValue("Campus", campus);
cmd.Parameters.AddWithValue("HelpCode", helpcode);
cmd.ExecuteNonQuery();
conn.Close();
add cmd.ExecuteNonQuery(); after your command is created and before you close the connection
Related
I'm using SSIS and am importing multiple (30) txt files. I create the table on the fly using the file name of the txt file and creating the columns based on the first row from the txt file - all this works. My code stops working when an apostrophe ' is in one of the fields.
The files are delimitated using a |
My code:
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["xxxxxxxxxxxxxx"].AcquireConnection(Dts.Transaction) as SqlConnection);
string line1 = "";
//Reading file names one by one
string SourceDirectory = #"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string[] fileEntries = Directory.GetFiles(SourceDirectory);
foreach (string fileName in fileEntries)
{
// do something with fileName
string columname = "";
//Reading first line of each file and assign to variable
System.IO.StreamReader file2 =
new System.IO.StreamReader(fileName);
string filenameonly = ((((fileName.Replace(SourceDirectory, "")).Replace(".txt", "")).Replace("\\", "")).Replace("-", "_"));
line1 = (" IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo]." + filenameonly + "') AND type in (N'U'))DROP TABLE [dbo]." + filenameonly + " Create Table dbo." + filenameonly + "([" + file2.ReadLine().Replace("|", "] NVARCHAR(500),[") + "] NVARCHAR(500))").Replace(".txt", "");
file2.Close();
SqlCommand myCommand = new SqlCommand(line1, myADONETConnection);
myCommand.ExecuteNonQuery();
MessageBox.Show("TABLE IS CREATED");
//Writing Data of File Into Table
int counter = 0;
string line;
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
columname = line.ToString();
columname = "[" + columname.Replace("|", "],[") + "]";
}
else
{
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + "')";
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
The offending line is:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + "')";
I tried amending to the below to replace the apostrophe to no avail:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + line.Replace("'''", "") + "')";
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("'", "") + "')";
Also nesting the replace does not work:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace(line.Replace("'''", ""),"|" ) + "')";
The below does not import anything:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','").Replace("'", "") + "')";
Changing to the below imports all but then fails over at the line with the apostrophe:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','").Replace("'''", "") + "')";
What am I missing?
Instead of concatenating the two REPLACE() functions like your first attempt, you should nest them.
Replace(
Replace({arguments to remove apostrophe character}),
{arguments to remove pipe character}
)
If you want to keep the C# usage of string.Replace(), you would nest like this:
line.Replace({arguments to replace apostrophe).Replace({arguments to replace pipe})
Or you could do it in two separate statements:
line = line.Replace({arguments to replace apostrophe});
line = line.Replace({arguments to replace pipe});
Hey My Insert Statement isn't Working I used the same code for inserting other panel data to excel sheet it's working perfectly there but when I'm trying to insert data in other sheet using second panel it's throwing exception "Insert INTO Statement is not valid" I check every single thing in this i can't find any mistake in it. I'm using OleDb For Insertion.
Here is the same code I've been using for first panel insertion.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
String filename1 = #"E:DB\TestDB.xlsx";
String connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(connection);
con.Open();
int id = 4;
string user = txtMUserName.Text.ToString();
string pass = txtMPassword.Text.ToString();
string role = txtMRole.Text.ToString();
DateTime date = DateTime.Now;
string Date = date.ToString("dd/MM/yyyy");
//string Time = date.ToLongTimeString();
string Time = "3:00 AM";
String Command = "Insert into [Test$] (UserID, UserName, Password, Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
OleDbCommand cmd = new OleDbCommand(Command, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Seems like you are using a reserved name for column Password. you need to escape it with []:
string Command = "Insert into [Test$] (UserID, UserName, [Password], Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here
I'm new to .net development
I'm trying to fetch the data from Facebook app,when update the query I'm getting the above error on update customer details
in 'cust_date' filed and i taken in cust_date datatype is DATETIME.
so how to convert this DATETIME format to 'MM/DD/YYYY HH:MM'
public void Customer(string Customerid)
{
var accessToken = "CAACEdEose0cBAMTINaTZCrm67pT6cO16KHsR3UNgOTZAGH03GHmhKozUOxEXYpL3ZB9pfbFWm4Oj2VMVy8xMf5vXMpFtY6LZm2Hej0WmrHPlwk7pWyibf9gXbCaDBoIih26nRqffAfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(Customerid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string fst_name = obj["first_name"].ToString();
string lst_name = obj["last_name"].ToString();
string link = obj["link"].ToString();
string[] splitlink = link.Split('/');
if (splitlink[3].StartsWith("profile"))
{
splitlink[3] =name.ToString();
link = splitlink[0] + '/' + splitlink[1] + '/' + splitlink[2] + '/' + splitlink[3];
}
string gender = obj["gender"].ToString();
string cust_updated_time = obj["updated_time"].ToString();
string abctime = cust_updated_time.Substring(0, cust_updated_time.ToString().Length - 3);
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy3 = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy3, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myOleConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy = "select * from fb_customer";
myOleConnection.Open();
SqlCommand myOleCommand = new SqlCommand(qy, myOleConnection);
myOleCommand.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,firstname,lastname,link,gender,cust_date,New) values('" + custid + "','" + name + "','" + fst_name + "','" + lst_name + "','" + link + "','" + gender + "','" + abctime + "','1')";
SqlDataReader myOleDataReader = myOleCommand.ExecuteReader();
myOleDataReader.Close();
myOleConnection.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = " UPDATE fb_customer set name='" + name + "',firstname='" + fst_name + "',lastname='" + lst_name + "',link='" + link + "',gender='" + gender + "',cust_date= '" + abctime + "' where customer_fb_id = '" + custid + "'";
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
public void IIPLCustomer(string iiplcustid, string abctime)
{
var accessToken = "CAACEdEose0cBADKYiSkFVcqeZAYxmYlytKM5pQT6zuEvnNoU9soPlWc2pZAJvKDL557BKTGIRNhbcuZBR6Li8TlrcM8yG1yXYGzikVlUPyFgDPzEDMiIZAnuHe5y3gTZCxkyTeA12ISPPRhJev6B63rTr05slMfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(iiplcustid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string[] splitname = name.Split(' ');
string link = obj["link"].ToString();
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(qy1, myConnection1);
myCommand1.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,link,firstname,lastname,cust_date,New) values('" + custid + "','" + name + "','" + link + "','" + splitname[0] + "','" + splitname[1] + "','" + abctime + "','1')";
SqlDataReader myReader1 = myCommand1.ExecuteReader();
myReader1.Close();
myConnection1.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = "SET DATEFORMAT MDY UPDATE fb_customer set name='" + name + "',firstname='" + splitname[0] + "',lastname='" + splitname[1] + "',link='" + link + "',cust_date='" + abctime + "' where customer_fb_id = '" + custid + "'";
//Here I'm getting an error
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
You can use Datetime.ParseExact method to convert date into appropriate format. Use like this
DateTime.ParseExact('07-12-2013', 'dd/MM/yyyy',
System.Globalization.CultureInfo.InvariantCulture).ToString('yyyy/MM/dd')
You need to change the format whatever you like.
This is gonna be very simple. Try the following format.
string date = DateTime.Now.ToString("MM/dd/yyyy HH:MM");
I just gave DateTime.Now and converted it. You can give the DateTime which you get and convert it to the format specified in the above syntax.