SELECT ODBC table and INSERT into SQL Server - c#

I have an ODBC connection to a database of which I need one table of data with 10 columns.
I need to insert this table into SQL Server database. I´ve tried to many ways to do it but still with any results.
OdbcConnection OCon = new OdbcConnection("Dsn=" + DbSource.SelectedItem.ToString());
SqlConnection SCon = new SqlConnection("Data Source=" + SrvrDD.SelectedItem.ToString() + ";database=" + DdDestiny.SelectedItem.ToString() + ";User ID=id;Password=pass");
OCon.Open();
SCon.Open();
String QrySelect ="SELECT * FROM " + GridCon.Rows[x].Cells[1].Value;
OdbcCommand commandC = new OdbcCommand(QrySelect, OCon);
String QryInsert = "INSERT INTO " + DdDestiny.SelectedItem.ToString() + ".dbo." + GridCon.Rows[x].Cells[2].Value + " VALUES (#Sql)";
SqlCommand commandD = new SqlCommand(QryInsert, SCon);
OdbcDataReader Oreader = commandC.ExecuteReader();
commandD.Parameters.Add("#Sql",SqlDbType.NVarChar, 5);
while (Oreader.Read())
{
string s = Oreader[0].ToString();
commandD.Parameters["#Sql"].Value = s;
commandD.ExecuteNonQuery();
}
Everything works fine but when commandB.ExecuteNonQuery(); get in, an error appears:
"The column name or the specified values do not correspond to the definition of the table."
Is the translation.

Related

MySQL SELECT INTO Variable, Getting 'Fatal Error encountered during command execution.'

I have tried MANY suggested solutions from here but nothing seems to work for this problem. I just keep getting this error message when it hits the 'mdr = command.ExecuteReader();' line. Any thoughts please?
try
{
MySqlConnection connection = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";");
MySqlCommand command;
MySqlDataReader mdr;
connection.Open();
string ThePID = tbPID.Text;
string TheRound = tbRound.Text;
string CurrentPage = tbCurrentPage.Text;
// SELECT #myvar:= myvalue
string query = "SELECT ImageURL, ProofingText " +
"INTO #ImageURL, #ProofingText " +
"FROM Rounds " +
"WHERE ProjectID = " + ThePID + " " +
"AND CurrentRound = " + TheRound + " " +
"AND Page = " + CurrentPage + ";";
command = new MySqlCommand(query, connection);
mdr = command.ExecuteReader();
mdr.Read();
rtProofing.Text = mdr.GetString("#PRoofingText");
tbURL.Text = mdr.GetString("#ImageURL");
tbImagePage.Text = Path.GetFileName(tbURL.Text);
PageBox.Image = Image.FromFile(tbURL.Text);
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you use MySqlConnector, you will get a helpful exception message that explains the problem:
Parameter '#ImageURL' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.
By default, MySQL queries (executed from .NET) can't use user-defined variables. You can relax this limitation by adding Allow User Variables=true to your connection string.
However, this won't fix your underlying problem, which is that this isn't the right way to select data from MySQL.
Firstly, your query is susceptible to SQL injection; you should rewrite it to use parameters as follows:
using (var command = connection.CreateCommand())
{
command.CommandText = #"SELECT ImageURL, ProofingText
FROM Rounds
WHERE ProjectID = #ThePID
AND CurrentRound = #TheRound
AND Page = #CurrentPage;";
commands.Parameters.AddWithValue("#ThePID", ThePID);
commands.Parameters.AddWithValue("#TheRound", TheRound);
commands.Parameters.AddWithValue("#CurrentPage", CurrentPage);
Then, you can retrieve the values with a slight variation on your current code. You must retrieve the values by their column names, which do not have a leading #. You should also check that a row was retrieved by examining the return value of Read():
if (mdr.Read())
{
rtProofing.Text = mdr.GetString("ProofingText");
tbURL.Text = mdr.GetString("ImageURL");
}
Finally, string concatenation is also not the right way to build a connection string. The MySqlConnectionStringBuilder class exists for this purpose; use it.
var builder = new MySqlConnectionStringBuilder
{
Server = server,
Database = database,
UserID = uid,
Password = password,
};
using var connection = new MySqlConnection(csb.ConnectionString);

How to insert an number value to a oracle db

i have a problem with my code. My code is working fine, but i want to insert a decimal number in my oracle table (the type of the field in oracle is number).
"Gewicht" is a textfield where the user have to type a decimal number in. actually i can insert just full numbers but i cant insert decimal.
my oracle datafields:
TOUR - VARCHAR2 (20 BYTE)
GEWICHT - NUMBER
I have no much experience about programming so i give my best. Its my first Script :).
private void insert()
{
try
{
String connectionString = "Data Source = (DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = IP-Adress)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = NAME)" +
")" +
");User Id = USER;password=password;";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values ('" + this.comboBox1.Text + "'," + Gewicht.Text+ ")";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Erfolgreich eingefügt");
comboBox1.Text = String.Empty;
Gewicht.Clear();
viewdata();
}
catch (Exception ex)
{
MessageBox.Show("Fehler");
}
You are missing quotes in your insert query string. In any case, use parameters like:
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values (#tour,#wicht)";
cmd.Parameters.Add("#tour", OracleDbType.NVarChar2).Value = this.comboBox1.Text;
cmd.Parameters.Add("#wicht", OracleDbType.Decimal).Value = Decimal.Parse(Gewicht.Text);

OleDB Connection String to MySQL Connection String

I have this OleDB code which basically reads an excel file and displays it on to the datagridview after a button click:
string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(pathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + txtSheet.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dgvViewDrivers.DataSource = dt;
My question is that how would I make a MySQL Connection out of this OleDB connection string? Please help me.
You need to use MySQL .NET connector
http://dev.mysql.com/downloads/connector/net/
using (MySqlConnection conn = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "sql here";
cmd.ExecuteNonQuery();
}
}
Your current code
This
using (vDBCon = new MySqlConnection("SERVER=localhost;Data Source=" + txtPath.Text + ";user=root;PASSWORD= ;"))
txtPath.Text needs to be the name of your database in MySQL. I assume you left the password out. If not you need one.
"SERVER=localhost;Data Source=MyDatabase;user=root;PASSWORD=MyPassword;"
where MyDatabase is the actual name of your database and MyPassword is the password you use to login with
You have to actually be running MySQL Server itself to create and connect to a MySQL database. it doesn't work of a file like Access. If you want something like that just use SQLite.
this
vCmd.CommandText = "SELECT * FROM [" + txtSheet.Text + "$]";
this you will be selecting data from your table in MySQL so it needs to look like
vCmd.CommandText = "SELECT * FROM MyTable";
where MyTable is actually the name of your table in the database

my update c# code is not working,can i update two relational table at once?

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

OleDbConnection s FillSchema doesn't change after alter table (Oracle)

I got a problem when using OleDbConnection in combination with an oracle Database.
When i request the schema of an existing Table using the OleDbConnection's FillSchema Method the result seems to get cached somehow.
To reproduce the Problem you need to do the followin steps:
create a table named cachetest with one column
Request a schema of the table cachetest in your code via FillSchema
Change the table by adding a column via alter table cachetest add column2 char(3)
request the schema of cachetest again. The Schema doesn't contain the column2
OleDbConnection connection = new OleDbConnection(
"Provider=" + "OraOLEDB.Oracle;"
+"Data Source=" + "datasource"
+ ";User Id=" + "msp" + ";"
+ "Password=" + "msp"
+";ChunkSize=1;" + "OLEDB.NET=" + "true;");
connection.Open();
DataTable dt = new DataTable("cachetest");
OleDbDataAdapter adapter_oledb =
new OleDbDataAdapter("select * from cachetest", connection);
adapter_oledb.FillSchema(dt, SchemaType.Source);
int columncount1 = dt.Columns.Count;
OleDbCommand command = new OleDbCommand("alter table cachetest add column2 char(30)", connection);
command.ExecuteNonQuery();
connection.Close();
OleDbConnection connection2 = new OleDbConnection(
"Provider=" + "OraOLEDB.Oracle;"
+"Data Source=" + "datasource"
+ ";User Id=" + "msp" + ";"
+ "Password=" + "msp"
+";ChunkSize=1;" + "OLEDB.NET=" + "true;");
DataTable dt2 = new DataTable("cachetest");
connection2.Open();
OleDbDataAdapter adapter_oledb2 = new OleDbDataAdapter(
"select * from cachetest", connection2);
adapter_oledb2.FillSchema(dt2, SchemaType.Source);
int columncount2 = dt2.Columns.Count;
This Problem doesn't appear using a SQL server...
Do you have any Idea how to solve this problem?
best regards martin

Categories