I add data from a text to excel with insert into, but it's always show string format. I want it float format(0.2, 1, 20) and I cant change them in excel (for example a coloumn in one time, only it could be changed by one by for all cells). I tried tryparse or converttoint32 func. but nothing change in excel, the numbers are still in text format..
public void ExcelWrite(string date, string station_name, string station_no, string xvaluee)
{
try
{ float j;
xvaluee=xvaluee.Trim();
float.TryParse(Valuee, out j);
string szConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C://data.xls';Extended Properties='Excel 8.0;HDR=YES'";
OleDbConnection conn = new OleDbConnection(szConn);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES('" + station_no + "','" + station_name + "','" + date + "','" + j + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
since you adding '' for each parameter all will take as strings
use Parameters as below
using(OleDbConnection cn = new OleDbConnection(szConn ))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES(?,?,?,?)", cn);
cmd1.Parameters.AddWithValue("#p1", station_no );
cmd1.Parameters.AddWithValue("#p2", station_name );
cmd1.Parameters.AddWithValue("#p3",date );
cmd1.Parameters.AddWithValue("#p4", j);
cmd1.ExecuteNonQuery();
}
Related
so I have this program which when I press a button inserts a record into an excel spreadsheet with, the columns, being , customer, product, weight, dateTime. Now I want to be able to update a record if the same customer, and product occurs, but I also want to add the previous weight field with the new field, and update the time.
The problem is i'm not sure how to modify my update statement to do this.
// Load data from database, and Update database if filed already exists
DataSet ds = new DataSet();
string insertquery = "SELECT * FROM [Sheet1$] where [Customer] = '" + lblcustomername + " ' ";
OleDbConnection myConnection = new OleDbConnection(OutputDatabaseConnectionString); //define new connection object
OleDbDataAdapter mydataadapter = new OleDbDataAdapter(insertquery, myConnection); //define data adaptor and select column data from spreadsheet
mydataadapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
// If item exists in database, update it
if (i > 0)
{
try
{
System.Data.OleDb.OleDbConnection myConnection2; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection2 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection2.Open();
myCommand.Connection = myConnection2;
sql = "UPDATE [Sheet1$] SET [Net Weight(Kg)]= '" + textBox1.Text + "' WHERE [Customer] = '" + lblcustomername + "'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection2.Close();
myConnection2.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// if it doesn't exist update database
try
{
System.Data.OleDb.OleDbConnection myConnection1; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection1 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection1.Open();
myCommand.Connection = myConnection1;
sql = sql = "INSERT INTO [Sheet1$] ([Customer],[Product],[Net Weight(Kg)], [DateTime]) VALUES('" + lblcustomername.Text + "','" + lblproductname.Text + "','" + textBox1.Text + "','" + (DateTime.Now).ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection1.Close();
myConnection1.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I've been working on this function to take a user selected csv file and parse it into an access database. After much trial and error and reading here, the thing will compile and run without crashing but no values are being inserted into the table. This I where I am at currently.
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
productFileName = productOpenDialog.SafeFileName;
productFilePath = Path.GetDirectoryName(productOpenDialog.FileName);
string connectionString = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source ={0}"+"\\VendorDB.accdb;Persist Security Info = False;", Environment.CurrentDirectory);
string selectSQL = String.Format(#"SELECT * FROM [" + productFileName + "]");
using (OleDbConnection connection = new OleDbConnection(String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Text;", productFilePath)))
{
using (OleDbCommand command = new OleDbCommand(selectSQL, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
//create connection to Access DB
OleDbConnection DBconn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//set cmd settings
cmd.Connection = DBconn;
//cmd.CommandType = CommandType.Text;
//open DB connection
DBconn.Open();
//read each row in the Datatable and insert that record into the DB
for (int i = 0; i < dataTable.Rows.Count; i++)
{
cmd.CommandText = "INSERT INTO Product_List (ProductID, ProductName, Description, InventoryItem, Price, CaseSize, SalespersonID)" +
" VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
"','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
"','" + dataTable.Rows[i].ItemArray.GetValue(6) + "')";
cmd.ExecuteNonQuery();
}
//close DB.connection
DBconn.Close();
}
}
}
}
I am aware that datatypes in fields might be an issue, so I removed a DateTime and changed price to a short number, so all data is strings and numbers. Despite successfully loading the DataTable from the csv file, no values are inserted into access.
I had make this small method to insert data from C# forms into my Oracle database. The code processed fine, but when I go to SQL Developer to check if the record has been inserted or not, I found nothing...
public void conn2db()
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statmentcmd = "insert into register_user (userid,username,pass,fullname,phonenum,gender,country) values (" + 1 + "," + textBox1.Text + "," + textBox2.Text + "," + textBox4.Text + "," + textBox5.Text + "," + radioButtonValue+ ","+comboBox1.Text+");";
OracleConnection conn = new OracleConnection(connstring);
conn.Open();
MessageBox.Show("connected to database");
OracleCommand cmd = new OracleCommand();
cmd.CommandText=statmentcmd;
cmd.Connection=conn;
OracleDataAdapter oda = new OracleDataAdapter(cmd);
MessageBox.Show(statmentcmd);
conn.Close();
MessageBox.Show("Connection closed");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try executing the command like this:
OracleCommand cmd = new OracleCommand();
cmd.CommandText = statmentcmd;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
Or more simply:
OracleCommand cmd = new OracleCommand(statmentcmd, conn);
cmd.ExecuteNonQuery();
try change the Copy to Output Directory : Do notcopy
Somehow I cannot understand what is going on with a command I am using.
Basically I want to insert data into an EXCEL file as following:
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=scriptsdb.xlsx;Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
string sSQLQuery = "INSERT INTO [Plan1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('" + NextID + "','" + txtbxName.Text + "','" + txtbxDescription.Text + "','" + txtboxSQL.Text + "')";
OleDbCommand cmd = new OleDbCommand(sSQLQuery, objConn);
objConn.Open();
cmd.ExecuteNonQuery();
Now check it out. Sometimes it works (record is added) and sometimes I get an error message (Operation must use an updateable query).
As weird as it might sound I just get the error message when the Text fields have just one word. e.g: "TEST". As soon as I change it to "TEST ONE" it works fine. If I try to save it with two words right from the beginning it works.
Any idea what I might be doing wrong?
Thanks!!
Note: change INSERT INTO [Plan1$] to INSERT INTO[Sheet1$].
Working code.
class Program
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+"C:\\Users\\123\\Desktop\\plan1.xlsx;"+"Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes\";";
// here you can use your text box or from
// where ever you access the data to be inserted
// into the that Excel file sheet
string selectString = "INSERT INTO [Sheet1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('1','maziz','Not working','selectfrom you')";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(selectString, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Successfully inserted the records");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
Console.ReadLine();
}
}
I have this code here:
public class clsDataLayer
{
// This function saves the personnel data
public static bool SavePersonnel(string Database, string FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try
{
// Retrieving information
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Inserting information into the table
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate +
"', '" + EndDate + "')";
// Gets the statement to execute at the data source
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Executes the SQL statement and returns the number of rows
command.ExecuteNonQuery();
// Closes the connection to the data source
conn.Close();
recordSaved = true;
}
catch (Exception)
{
recordSaved = false;
}
return recordSaved;
}
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// States the classes used
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Defines sqlConnclass and what each will consist of
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Defines DS and what each will consist of
DS = new dsUserActivity();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblUserActivity);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
public clsDataLayer()
{
}
public static dsPersonnel GetPersonnel(string p)
{
throw new NotImplementedException();
}
}
I need to add this code but everytime I do I get an error that says No overload for method 'GetPersonnel' takes '1' arguments
// This function gets the user activity from the tblPersonnel
public static dsPersonnel GetPersonnel(string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
//create the connection string
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
string query;
if (strSearch == "" || strSearch.Trim().Length == 0)
{
query = "SELECT * from tblPersonnel";
}
else
{
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
}
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblPersonnel", sqlConn);
// Defines DS and what each will consist of
DS = new dsPersonnel();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblPersonnel);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SavePersonnel(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblPersonnel (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
It looks like you're defining
public static dsPersonnel GetPersonnel
twice in the same class. I suspect you are REPLACING the single-arg version with the two-arg version but somewhere you're still calling the single-arg version.
I know you're not asking for this sort of input, but I can't help myself...
You should wrap your OleDbConnections in a using block to make sure they get closed like so:
using (OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database))
{
conn.Open();
...
{
Not sure where your strSearch data is coming from, but you're setting yourself up for a nasty SQL Injection attack with this line:
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
you should use SQL parameters or a stored procedure.