I'm trying to execute multiple updates like this
UPDATE clients SET name = :name WHERE clientId = :clientID
I've tried something like this
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
"begin " +
" UPDATE clients SET name = " + name1 + " WHERE clientId = " + clientId1 +
" UPDATE clients SET name = " + name2 + " WHERE clientId = " + clientId2 +
"end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
but I need to execute hundreds of parameterized updates like the first one
Related
Let's say I have a query result that looks as follows:
ID NAME Phone
---- ---- -----
1 John 123456
2 John 125678
3 John 345678
4 Abby 456789
5 Abby 567890
I want to return just a single row instance of name: John, where the phone number like '12%'.
In c#, I wrote this syntax to get the PersonName variable as the result of the query.
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
connection.Close();
I don't know whats wrong with my code but the PersonName returns null. What did I do wrong?
We have to be missing something else here. Try the following code sample based on what you provided:
try {
MySqlConnection connection = new MySqlConnection("SERVER=localhost;DATABASE=testdb;UID=root;PASSWORD=;");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
I have a feeling that for some reason the call to .Open() is failing and the error is being swallowed elsewhere. Try the above and let me know what you find out.
do this : change this (string)command.ExecuteScalar(); by Convert.ToString(command.ExecuteScalar());
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = Convert.ToString(command.ExecuteScalar());
connection.Close();
hello guys i have problem with running update query from Microsoft access 2013 i just want to update client table with client id and name and phone i cant get the data to be update always error in syntax
string I = "UPDATE client SET client.ID =" + ID.Text + " ,client.Name =" + Name.Text + " ,client.Phone = " + Phone.Text + " WHERE client.ID="+ ID.Text +"";
command.CommandText = I;
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
You need to use a parameterized query, like this:
string I = "UPDATE client SET client.Name = ?, client.Phone = ? WHERE client.ID = ?";
command.CommandText = I;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("?", Name.Text);
command.Parameters.AddWithValue("?", Phone.Text);
command.Parameters.AddWithValue("?", ID.Text);
connection.Open();
command.ExecuteNonQuery();
Note that it makes no sense to "SET" client.ID since it is not going to change.
I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];
So I have a table with the following columns:
ID, name, adress, etc..
I have been doing some research but I cannot come across the right keywords to find out to do what I want. I would like to be able to take the name value (Which would be say... "John Doe" which is in the database already for sure..) and retrieve the ID of it (from the int MySQL value ID).
I have come across the following code but I cannot seem to figure out how to extend its limits to match my needs.
connection2.Open();
cmd.ExecuteNonQuery();
try
{
MySqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(myReader.GetOrdinal("id")));
}
myReader.Close();
}
finally
{
connection2.Close();
}
This is also what I have come up with to the best of my abilities.
MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
string query = #"SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
MySqlCommand cmd = new MySqlCommand(query, connection2);
You should replace the hard coded parameters with sql parameters, but here is a general idea of what you'll need to do here. Using your present sql query.
MySqlConnection sqlConn = new MySqlConnection();
MySqlCommand sqlCmd = new MySqlCommand();
string sSql = "SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
sqlConn.ConnectionString = "Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";";
sqlCmd.CommandText = sSql;
sqlCmd.CommandType = CommandType.Text;
sqlConn.Open();
sqlCmd.Connection = sqlConn;
MySqlDataReader reader = sqlCmd.ExecuteReader();
List<string> results = new List<string>();
while (reader.Read())
{
results.Add((reader["id"].ToString());
}
reader.Close();
sqlConn.Close();
Keep in mind you can add the reader results to a string, to a list like above, whatever you want to do with it.
this how id en name pawe
clsMySQL.sql_con.Open();
string id = ID;
sql = "SELECT *FROM test";
cmd = new MySqlCommand(sql, clsMySQL.sql_con);
sql_cmd = new MySqlCommand(sql, clsMySQL.sql_con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr["id"].ToString();
user = dr["user_name"].ToString();
pass = dr["password"].ToString();
if (name.Text == user && passw.Text == pass)
{
string depart = id;
Hide();
MessageBox.Show("it works");
// Then show the main form
cracker form = new cracker(name.Text);
form.sid = depart;
form.Show();
MessageBox.Show(ID);
}
}
else
{
MessageBox.Show("Invalid Login please check username and password");
}
clsMySQL.sql_con.Close();
}
first time I'm doing an insert from ASP.NET/C# and I'm having a little issue. I keep getting the following error every time this code runs: " ExecuteNonQuery: CommandText property has not been initialized" Does anyone know what this means and how I fix it?
Thanks in advance!
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += "VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = dataConnection.CreateCommand())
{
dataConnection.Open();
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
dataCommand.Parameters.Add("#Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Rep", repID);
dataCommand.Parameters.Add("#Reason", txtReason.Text);
dataCommand.Parameters.Add("#Contact", txtContact.Text);
dataCommand.Parameters.Add("#CaseNum", txtCaseNum.Text);
dataCommand.Parameters.Add("#Comments", txtComments.Text);
dataCommand.Parameters.Add("#PropertyID", lstProperties.SelectedValue);
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += " VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection))
{
dataCommand.Parameters.AddWithValue("Today", DateTime.Today.ToString());
dataCommand.Parameters.AddWithValue("Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Rep", repID);
dataCommand.Parameters.AddWithValue("Reason", txtReason.Text);
dataCommand.Parameters.AddWithValue("Contact", txtContact.Text);
dataCommand.Parameters.AddWithValue("CaseNum", txtCaseNum.Text);
dataCommand.Parameters.AddWithValue("Comments", txtComments.Text);
dataCommand.Parameters.AddWithValue("PropertyID", lstProperties.SelectedValue);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
Copy-paste should do the trick
This usually means you haven't set the CommandText property, but in your case, you have.
You should try testing that the sqlQuery string is actually not empty at this line:
dataCommand.CommandText = sqlQuery;
P.S. As a "best practice", you may want to consider opening the connection AFTER setting up the SqlCommand object, to minimize the time spent with an open connection:
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
//...
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
Looking at your string sql query, you're not leaving a space between the "INTO" part and "VALUES" part.
...............Property_ID)";
sqlQuery += "VALUES (#Today, ..............
SHOULD BE:
...............Property_ID)";
sqlQuery += " VALUES (#Today, ..............