I need to run several queries inside one function. My working code for single query is as below:
C# Code:
try
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.0.0.24)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DEVL)));User Id=aaziz;Password=123211;";
con.Open();
string cmdQuery = "Insert into M.person (RED_NO, USED_FLAG) VALUES ('12', '0')";
OracleCommand cmd = new OracleCommand(cmdQuery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
How to modify it to accommodate multiple SQL queries?
try
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.0.0.24)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DEVL)));User Id=aaziz;Password=123211;";
con.Open();
string cmdQuery = "Insert into M.person (RED_NO, USED_FLAG) VALUES ('12', '0')";
OracleCommand cmd = new OracleCommand(cmdQuery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT NEW QUERY HERE";
cmd.ExecuteNonQuery();
con.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Related
I have an update statement that works fine when I run it from SQL Developer. However, when I try to run it in C#, the program will freeze on the line that executes the command and not output anything. I have it defined as follows below:
private static OracleCommand cmd = new OracleCommand();
private static OracleConnection conn = new OracleConnection();
conn.ConnectionString = Properties.Settings.Default.myconstring;
cmd.Connection = conn;
cmd.CommandText = "UPDATE mytable SET PARAM1 = :param1 WHERE PARAM2 = :param2";
cmd.CommandType = CommandType.Text;
cmd.BindByName = true;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":param1", OracleDbType.Single)).Value = param1Val;
cmd.Parameters.Add(new OracleParameter(":param2", OracleDbType.Int32)).Value = param2Val;
conn.Open();
try {
cmd.ExecuteNonQuery(); //Freezes here
} catch(Exception e) {
MessageBox.Show(e.ToString());
}
conn.Close();
I have verified my values being put in are correct.
I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}
I have listview control in my page. I gets populated onPage load as well as when new record entered in the table. Problem is after performing InsertOperation I am calling It's bind method again but it doesn't refresh its data. Hence I debugged it & executed actual query in SQL & query returns with added rows.
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
this.bindBulkPricing();
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
private void bindBulkPricing()
{
string action = Request.QueryString("action").ToString;
if (action == "new") {
productID.Text = rowNumber;
}
try {
string str = "select * from bulk_pricing where productID = #productID";
string conString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString;
MySqlConnection con = new MySqlConnection(conString);
MySqlCommand cmd = new MySqlCommand(str);
cmd.Parameters.AddWithValue("#productID", productID.Text);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
bulkPriceList.DataSource = dt;
bulkPriceList.DataBind();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.bindBulkPricing();
} catch (Exception ex) {
Response.Write(ex);
}
}
You only run cmd.ExecuteNonQuery() after run this.bindBulkPricing(). I hope it will work for you.
I'm a beginner and trying to create a simple program in C# for inserting and updating records in an Oracle database. I have managed to successfully connect to the database but I'm getting an exception for my SQL statement which states that (?) symbol is not supported. Why am I getting this exception and how can I fix this?
My code is:
private void btnSave_Click(object sender, EventArgs e)
{
OracleConnection con = null;
try
{
con = new OracleConnection();
string constr = "Data source=XE; User ID=cloudester; Password=cloudester123;";
if (con.State != ConnectionState.Open)
{
try
{
con.ConnectionString = constr;
con.Open();
//MessageBox.Show("Successfull connection");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught");
}
}
if (con.State == ConnectionState.Open)
{
string str = "Insert into EMP_DETAIL(EmpId, Name, Age)";
str += "values (?,?,?)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = Text;
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
}
}
catch { ... }
}
You need to use the named parameter for your command
string str = "Insert into EMP_DETAIL(EmpId, Name, Age) values (:EmpId, :Name, :Age)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = str; //cmd.CommandText = Text; not sure why did you use Text here
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
As agent5566 said, and from OracleCommand.Parameters property;
When using named parameters in an SQL statement called by an
OracleCommand of CommandType.Text, you must precede the parameter name
with a colon (:)
Use them like;
using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"Insert into EMP_DETAIL(EmpId, Name, Age)
values (:EmpId, :Name, :Age)";
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
con.Open();
cmd.ExecuteNonQuery();
}
By the way, System.Data.OracleClient has been marked as deprecated in .NET 4 version. You might wanna use Oracle Data Provider for .NET instead.
As an alternative, DataDirect and DevArt also have their own oracle providers for .NET.
I'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/