hello i have create a table buy_unit in oracle database
CREATE TABLE buy_unit(
unit_id NUMBER(10) not null PRIMARY KEY,
unit_name VARCHAR2(10) not null
);
and insert Values
INSERT INTO BUY_UNIT
values(001,'Liter');
desc SELL_BUY_UNIT;
then create a combo box combobox1 in C# now can load buy_unit table data in combobox ? i have use the connection:
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=XE;User ID=user1;password=pssword");
Well, you can see below code which is refering SQLConnection. You can change as per your DB may be OracleConnection or so. While using SQL, we have pass connection string with UID and PWD.
For Oracle
have connection string as
string con = "Data Source=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST = 000.00.0.00)(PORT = 0000)))(CONNECT_DATA =(SERVICE_NAME = database)));User ID=User/Schema;Password=password;Unicode=True";
public void BindComboBox()
{
SqlConnection con = new SqlConnection(#"server=ServerName; database = DBName ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select desire column from table";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "name to display";
cbSupportID.ValueMember = "id";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
and try to use using block when you open DB connection as below
using (OracleConnection objConn = new OracleConnection(con))
{
\\ you code
\\ do your stuff
}
Code for Oracle. Excuse for syntax.
public void Fillcombo()
{
string oradb = " Data Source=xe;User Id=dbname;Password=pws; ";
string query = "select id , name from table";
OracleConnection condatabase = new OracleConnection(oradb);
OracleCommand cmddatabase = new OracleCommand(query, condatabase);
try
{
condatabase.Open();
OracleDataReader myReader = cmddatabase.ExecuteReader(); ;
myReader = cmddatabase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetInt32(0).ToString();
comboBox1.Items.Add(sname.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
Am trying to read a table from a Mysql database and store all of it in a ms sql server in c# am reading from mysql correctly my problem is how to store the data i read in ms sql in the second part of code
string constring= ConfigurationManager.ConnectionStrings["cnxMysql"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0",conn);
conn.Open();
cmd.ExecuteNonQuery();
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt",conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
conn2.Close();
conn.Close();
I have a reverse issue, I have to transfer data from MS SQL Server to MySQL.
I have used below snippet for this, but I personally don't recommend this for production as it adds data one by one row. But you can use it for a small dataset or local environment. You can add a try-catch as well as customize as per your need. This is for just reference.
public void Main()
{
var table = GetDataTableFromSQLServer();
AddToMySQL(table);
}
private DataTable GetDataTableFromSQLServer()
{
var connection = GetSqlServerConnection();
string query = "SELECT Column1, Column2 FROM TableName WHERE Column3 is NOT NULL";
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
connection.Close();
return table;
}
private void AddToMySQL(DataTable table)
{
var connection = GetMySQLConnection();
connection.Open();
string query = "INSERT INTO TableName (column1, column2) VALUES(#column1, #column2);";
int i = 0;
foreach (DataRow row in table.Rows)
{
if (i % 1000 == 0)
{
// Closing & Reopening connection after 1000 records
connection.Close();
connection.Open();
}
Console.WriteLine($"Adding ({++i}/{table.Rows.Count})");
MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.Add(new MySqlParameter("#column1", MySqlDbType.Int64) { Value = row.Field<long>("column1").Trim() });
command.Parameters.Add(new MySqlParameter("#column2", MySqlDbType.VarChar) { Value = row.Field<string>("column2").Trim() });
var affectedRows = command.ExecuteNonQuery();
}
connection.Close();
}
private SqlConnection GetSqlServerConnection()
{
string connectionString = #"Data Source=...";
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
private MySqlConnection GetMySQLConnection()
{
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder
{
Server = "...",
Database = "...",
UserID = "...",
Password = "...",
Port = 3306
};
MySqlConnection connection = new MySqlConnection(connectionBuilder.ToString());
return connection;
}
Refer below code, you can optimize this code as there is alot of space for optimization but this is simple for beginner to understand basic level:
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0", conn);
conn.Open();
DataSet data;
using (MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(mySqlCommand))
{
data = new DataSet();
sqlAdapter.Fill(data);
}
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
conn2.Open();
for (int i = 0; i < data.Tables[0].Rows.Count; i++)
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt(column1,column2) values(#col1,#col1)", conn2);
cmd2.Parameters.AddWithValue("col1", data.Tables[0].Rows[i][0].ToString());
cmd2.Parameters.AddWithValue("col12", data.Tables[0].Rows[i][1].ToString());
cmd2.ExecuteNonQuery();
}
conn2.Close();
conn.Close();
Background
I've written a function that retrieves data using a SQL query and then outputs that data to a label. At the moment the search string is hard coded to "1002". The function is fired on a button click event.
Question
How do I pass data into my SQL query from a textbox so my search string is the contents of the text box, instead of 1002?
Code
private void getInfoStationID()
{
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = 1002";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, ConnStr);
DataSet question = new DataSet();
Adpt.Fill(question);
foreach (DataRow dr in question.Tables[0].Rows)
{
nameTtb.Text += question.Tables[0].Rows[0]["stationname"].ToString();
}
}
Change the query to:
string constring = #""; // Declare your connection string here.
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationId";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand command = new SqlCommand(SQL ,con);
and then you have to add parameter to the command object like this:
command .Parameters.Add("#StationId",SqlDbType.NVarChar).Value = textbox.Text;
Now you might be wondering why I have used parameters in the query. It is to avoid SQL Injection.
DataSet ds = new DataSet();
SqlDataAdapter adb = new SqlDataAdapter(command);
adb.Fill(ds);
con.Close();
And now you can iterate like this...
foreach (DataRow row in ds.Tables[0].Rows)
{
}
And you have to initialise the connection object and pass your connection string in it.
You can change your SQL string to use a variable, like #StationID, then add the variable to the query from textbox.text
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationID";
SqlCommand cmd = new SqlCommand;
cmd.CommandText = SQL;
cmd.CommandType = CommandType.Text;
cmd.Connection = ConnStr;
cmd.Parameters.AddWithValue("#StationID", Textbox1.Text);
da = new SqlDataAdapter(cmd);
DataSet nds = new DataSet();
da.Fill(nds);
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
string SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #stationID";
SqlCommand command = new SqlCommand(SQL, ConnStr);
command.Parameters.Add(new SqlParameter("#stationID", SqlDbType.Int));
command.Parameters["#stationID"].Value = textbox.Text;
I am new on C# . I create a C# Console program and insert some data to MySql by following code .
string connection = "Server=localhost;Database=user_table;Uid=root;Pwd=";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand cmd;
dbcon.Open();
cmd = dbcon.CreateCommand();
cmd.CommandText = "INSERt INTO user_table(user_name,amount) VALUES(#user_name,#amount)";
cmd.Parameters.AddWithValue("#user_name","Niloy");
cmd.Parameters.AddWithValue("#amount", "456");
cmd.ExecuteNonQuery();
Now I want to retrieve this data and display in console application .
like This
Niloy 234
Joy 500
Minal 230
how can i do this ?
You have to do the opposite of that you have already done for the insertion of data.
// You sql command
MySqlCommand selectData;
// Create the sql command
selectData = dbcon.CreateCommand();
// Declare the sript of sql command
selectData.CommandText = "SELECT user_name, amount, FROM user_table";
// Declare a reader, through which we will read the data.
MySqlDataReader rdr = selectData.ExecuteReader();
// Read the data
while(rdr.Read())
{
string userName = (string)rdr["user_name"];
string amount = (string)rdr["amount"];
// Print the data.
Console.WriteLine(username+" "+amount);
}
rdr.Close();
using (dbcon)
{
dbcon.Open();
cmd = dbcon.CreateCommand();
cmd.CommandText = "Select user_name,amount from user_table";
MySqlReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
Console.WriteLine(sqlreader[0].ToString()+ " "+(sqlreader[1].ToString());
}
sqlreader.Close();
}
You can use gridview to display your data, Using the similar way you used to insert data into your Table.
string connection = "Server=localhost;Database=user_table;Uid=root;Pwd=";
MySqlConnection dbcon = new MySqlConnection(connection);
DataTable dt = new DataTable();
MySqlCommand cmd;
dbcon.Open();
cmd = dbcon.CreateCommand();
cmd.CommandText = "SELECT * from user_table";
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
Gridview1.DataSource=dt;
Gridview1.DataBind();
I am adding a select statement from a mySQL database to a dataset but it does not fill the dataset.
Can anyone tell me what is wrong with my code?
string connString = "server = bla; user id = bla; Password = bla; database = bla;";
string query = "Select * From oc_product;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand mysqlcmd = new MySqlCommand(query, conn);
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(mysqlcmd);
da.Fill(dsProducts);
conn.Close();
How can you connect the result of a query from one database and insert it into another in a c# application?
This is what I have so far but it doesnt work.
// select from first database
string sCMD_All = "SELECT * FROM table";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
using (SqlConnection myConn = new SqlConnection(ConnectionString))
{
using (SqlCommand myCommand = new SqlCommand(sCMD_All, myConn))
{
myConn.Open();
SqlDataReader reader = myCommand.ExecuteReader();
da.Fill(ds);
myConn.Close();
}
}
DataTable sqTable = ds.Tables[0];
//insert into 2nd database
DataTable newTable = new DataTable();
newTable = sqTable;
using (SqlConnection myConn = new SqlConnection(ConnectionString_M))
{
string sCMD_I = "INSERT INTO tableNew #newTable";
using (SqlCommand myCommand = new SqlCommand(sCMD_I, myConn))
{
myConn.Open();
SqlDataReader reader = myCommand.ExecuteReader();
myConn.Close();
}
}
var commandText =
#"insert into [server].[database2].[schema].[table] (col1, col2, ...)
select col1, col2, ... from [server].[database1].[schema].[table]";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandText, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
NOTE: If databases are located on different servers, you should link servers:
exec sp_addlinkedserver #server = 'server2'