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();
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();
i am making a program in visual studio code with C#, it is a paid program so it needs an hwid system. Basically i want it to check if your computer HWID exists in the HWID table in my users database. But it says it can't connect to the database. Can you help me? This is my code.`
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
MySqlConnection mydbCon = new MySqlConnection(connectionString);
mydbCon.Open();
MySqlCommand command = mydbCon.CreateCommand();
command.CommandText = "SELECT * FROM yourTable WHERE hwid = GetHDDSerial";
IDataReader reader = command.ExecuteReader();
`
It could be that the connection string isn't formatted the way the MySQL connector wants it. The MySQL documentation shows "uid" instead of User, and "pwd" instead of Password. https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-connection-string.html
This should do what you need:
string connectionString = "Server=SomeServer;Database=i got you this is notthe real database;User ID=same;Password=same for password;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
string sql = "SELECT * FROM yourTable WHERE hwid = #val1";
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Parameters.AddWithValue("#val1", "GetHDDSerial");
connection.Open();
using (MySqlDataAdapter adapter = new MySqlDataAdapter())
{
using (DataSet ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
// Do something here. You can access the data like this:
// row["Id"] or whatever your field names are.
// int id = (int) row["Id"];
// Of course, I don't know your field names, so you'll have to complete this.
}
}
}
}
}
}
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);
}
}
I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();
I have question about using why i can not use the same instance of SQLCommand more than one time in the same code?
I tried the code down here and it runs good for the gridview but when i changed the query by using cmd.CommandText() method it keeps saying:
There is already an open DataReader associated with this Command which must be closed first.
This is the code:
string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select top 10 FirstName, LastName, Address, City, State from Customers";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
finally
{
con.Close();
}
The problem is that you are using the SqlCommand object to generate a DataReader via the command.ExecuteReader() command. While that is open, you can't re-use the command.
This should work:
using (var reader = cmd.ExecuteReader())
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
//now the DataReader is closed/disposed and can re-use command
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
There is already an open DataReader associated with this Command which must be closed first.
This is the very reason you don't share a command. Somewhere in your code you did this:
cmd.ExecuteReader();
but you didn't leverage the using statement around the command because you wanted to share it. You can't do that. See, ExecuteReader leaves a connection to the server open while you read one row at a time; however that command is locked now because it's stateful at this point. The proper approach, always, is this:
using (SqlConnection c = new SqlConnection(cString))
{
using (SqlCommand cmd = new SqlCommand(sql, c))
{
// inside of here you can use ExecuteReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// use the reader
}
}
}
These are unmanaged resources and need to be handled with care. That's why wrapping them with the using is imperative.
Do not share these objects. Build them, open them, use them, and dispose them.
By leveraging the using you will never have to worry about getting these objects closed and disposed.
Your code, written a little differently:
var cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
var gridSql = "Select top 10 FirstName, LastName, Address, City, State from Customers";
var cntSql = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand(gridSql, con))
{
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
using (SqlCommand cmd = new SqlCommand(cntSql, con))
{
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
}
Thank u quys but for the guys who where talking about using block !
why this code work fine which i seen it on example on a video ! It's the same thing using the same instance of SqlCommand and passing diffrent queries by using the method CommanText with the same instance of SqlCommand and it's execute just fine , this is the code :
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Delete from tbleProduct where ProductID= 4";
int TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "Insert into tbleProduct values (4, 'Calculator', 100, 230)";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "ypdate tbleProduct set QtyAvailbe = 234 where ProductID = 2";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
}