inserting xls file values into the odbc database - c#

i want to insert my xls file sheet into the ODBC server in c# .....kindly help me out with its c# coding....I can only find sql server related problems in the internet as i want to work in ODBC.
this is my coding :-
string ConnectionString, str;
OdbcConnection con;
OdbcCommand cmd;
SqlBulkCopy bkcp ;
private void btnSend_Click(object sender, EventArgs e)
{
string ConnectionString = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=ak_db.excel_table;Uid=root;Pwd=root";
using (OdbcCommand cmd = new OdbcCommand(ConnectionString))
{
OdbcCommand command = new OdbcCommand("Select * FROM [Sheet1$]", con);
con.Open();
// Create OdbcDataReader to Data Worksheet
using (OdbcDataReader dr = cmd.ExecuteReader())
{
// SQL Server Connection String
string OdbcConnectionString = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=ak_db.excel_table;Uid=root;Pwd=root";
}
i dont know what to do after this ...so kindly help me out....

One way to go is to read the values from your excel file and store them in a dataset like described here:
Reading-Excel-Files-From-C-Sharp
and then writing this dataset to your online database:
saving-dataset-to-database
Good Luck!

Related

Syntax error in From clause (easiest from clause possible)

I have an error in my easiest From clause (ErrorCode: -2147217900) and I do not know why...
Here my Code:
static string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\\P-OT-MT\\P-OT-DB.accdb; Jet OLEDB:Database Password=*************;";
public static DataSet DS_USERS;
public static void INIT_DS()
{
// Initialize the USERS dataset and write the database information to it
DS_USERS = new DataSet();
string SQL = "SELECT * FROM USER;";
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
Conn.Open();
OleDbCommand cmd = new OleDbCommand(SQL, Conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(DS_USERS);
cmd.Dispose();
adapter.Dispose();
Conn.Close();
}
}
I dont get where the error is... the Table USER is existant and the location of the Database is also correct... The password is correct too...
I hope you can help me
USER is a reserved word in MS Access.
See: List of reserved words in Access 2002 and in later versions of Access
You have to escape the word using [].
Use: string SQL = "SELECT * FROM [USER];";

C# Read from .DBF files into a datatable

I need to connect to a .dbf file in visual Studio using C# and populate a data table. Any ideas? I can currently view the tables in Visual Fox Pro 9.0
Code I have tried and failed, keep getting
External table is not in the expected format.
private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;
void test2()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
conn.Open();
sqlStr = "Select * from Clients.dbf";
//Make a DataSet object
myDataSet = new DataSet();
//Using the OleDbDataAdapter execute the query
myAdapter = new OleDbDataAdapter(sqlStr, conn);
//Build the Update and Delete SQL Statements
OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);
//Fill the DataSet with the Table 'bookstock'
myAdapter.Fill(myDataSet, "somename");
// Get a FileStream object
FileStream myFs = new FileStream
("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
// Use the WriteXml method of DataSet object to write XML file from the DataSet
// myDs.WriteXml(myFs);
myFs.Close();
conn.Close();
}
This code worked for me!
public DataTable GetYourData()
{
DataTable YourResultSet = new DataTable();
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");
// if including the full dbc (database container) reference, just tack that on
// OleDbConnection yourConnectionHandler = new OleDbConnection(
// "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from CLIENTS"; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(YourResultSet);
yourConnectionHandler.Close();
}
return YourResultSet;
}
Visual FoxPro DBFs are NOT dBase IV DBFs, and as such are unreadable by most versions of Microsoft Access's Jet database engine. (MSDN has some specifics, if you care.)
You'll need to either export the DBF from FoxPro into an actual dBase format, or you'll need to have C# open it using the Visual FoxPro OLEDB provider.
Once you have the provider installed, you'll need to change the "Provider" argument of your connection string to the following, assuming your DBF is in that folder.
Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\;
(Use an #"" string format; you missed a slash in the code sample, between PC1 and Documents.)

Need help on deleting row(s) from a SQL Server CE database

Another question today. This time, I'm having trouble deleting a row from a SQL Server CE database.
private void Form1_Load(object sender, EventArgs e)
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\userDtbs.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM history", connection);
DataSet data = new DataSet();
adapter.Fill(data);
//Delete from the database
using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
{
com.ExecuteNonQuery();
}
// Save data back to the databasefile
var cmd = new SqlCeCommandBuilder(adapter);
adapter.Update(data);
// Close
connection.Close();
}
My program's giving me an error telling me that connection is in a closed state, and I can't figure out why it would close before the DELETE command is executed.
Note that: executing command with Command.ExecuteXXX() requires the connection to be open first. Filling data into DataSet using SqlDataAdapter.Fill doesn't require that because it handles that internally. Executing the SQL query this way is direct and don't require any Update method call on adapter (as you add in your code after deleting). Update is just for saving changes made on your DataSet.
//Delete from the database
using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
{
if(connection.State == ConnectionState.Closed) connection.Open();
com.ExecuteNonQuery();
}

connect to mysql using c#

please excuse me for asking a primary question. I need to connect to this link http://sunspares.millenniumit.com/phpmyadmin/ using c#. It is of MySQL and i need to access a table called 'spares' in the 'inventory' database. Can anyone help me to initialize this connection using C#. I found the below coding but i'm confused how to provide the exact server that i need to be connected as well as to the table
con = mysql_connect("localhost","username","password");
Install the mysql connector/net.
Create a new project.
Add reference to: MySql.Data.
Add using MySql.Data.MySqlClient;.
Add the following code to your application:
private void button1_Click(object sender, System.EventArgs e)
{
string MyConString = #"SERVER=localhost;
DATABASE=mydatabase;
UID=testuser;
PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
}
<connectionStrings>
<add name="MySQLConnectionString" connectionString="server=localhost;User Id=root;pwd=;database=data1;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
-----------------------
using MySql.Data.MySqlClient;
...
MySqlConnection Conn = new MySqlConnection();
Conn = new MySqlConnection(ConnStr);

Error in asp.net c# code (mysql database connection)

My code is to update a record if it already exists in database else insert as a new record.
My code is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
MyConnection.Open();
String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("", TextBox3.Text);
using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
MyCmd1.ExecuteNonQuery();
}
else
{
// set the SQL string
String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
"VALUES (?,?,?)";
// Create the Command and set its properties
OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
objCmd.Parameters.AddWithValue("", HiddenField4.Value);
objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
objCmd.Parameters.AddWithValue("", TextBox3.Text);
// execute the command
objCmd.ExecuteNonQuery();
}
}
}
I am getting the error as:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009',' &' at line 1
The datatype for fields in table temp_save are:
fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
Please help me to resolve my error.
order is a reserved word. For a complete list of Reserved Words, please review this document.
You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)
INSERT INTO temp_save (fil_no,`order`,orderdate)....
i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql
String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";

Categories