I create simple mysql update statement in c#
string old_string = string.Empty;
string new_string = string.Empty;
using (MySqlConnection cn = new MySqlConnection("Server=hostaddress;Port=3306;Database=dbName;Uid=username;Pwd=password;"))
{
cn.Open();
try
{
string sql_old = #"select * from TBL_VERSION WHERE Id = 1 LIMIT 1";
using (MySqlCommand cmd = new MySqlCommand(sql_old, cn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
old_string = reader["pos"].ToString();
}
}
string sql = #"UPDATE TBL_VERSION SET pos = '2222' WHERE Id = 1";
using (MySqlCommand cmd = new MySqlCommand(sql, cn))
{
var x = cmd.ExecuteNonQuery();
}
string sql_new = #"select * from TBL_VERSION WHERE Id = 1 LIMIT 1";
using (MySqlCommand cmd = new MySqlCommand(sql_new, cn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
new_string = reader["pos"].ToString();
}
}
cn.Close();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
Then the database autocommit was set to 1, in the visual studio debugging the table was updated Ex. old_string = "5555" and new_string = "2222".
But if I try to check in other mysql client tools like SQLYog the record was not change when I try to run a same select statement, but if run the update statement direct to SQLYog, the record was successfully updated, then if I debug again the application the its already update.
Is any body encounter this problem?
Related
I need to insert into a table "pass" or "fail", if from the query done there is a single fail instead of 'RProva' I have to put "fail" if the query can't find a single fail instead of 'RProva' I have to insert "pass", the query is working but I can't figure out how to do the if with the results of a query, maybe I have to use a "for"? Don't know. It is the attempt to make it, the second is the query where I have to insert the result of the possbile "IF"
1.
SqlCommand cmdRD = new SqlCommand("SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1");
var RD = cmdRD.ExecuteScalar();
var values = new List<string>();
using (cmdRD,sqliteCon)
{
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
2.
SqlCommand cmd1 = new SqlCommand("INSERT INTO tSD(NomeItem,ResItemDet,DateStartDet,DateEndDet) OUTPUT inserted.Id VALUES (#NI,#RProva,#DATESE,#DATEED)");
cmd1.Parameters.AddWithValue("#DATESE", DATESE);
cmd1.Parameters.AddWithValue("#DATEED", DATEED);
cmd1.Parameters.AddWithValue("#NI", NI);
using (cmd1,sqliteCon)
{
foreach (var value in values)
{
if (value.Equals(pass))
{
cmd1.Parameters.AddWithValue("#RProva", value);
}
else
{
cmd1.Parameters.AddWithValue("#RProva", fail);
}
cmd1.ExecuteNonQuery();
}
}
int generatedId = Convert.ToInt32(cmd1.ExecuteScalar());
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("UPDATE tSE SET FK_TSD_id = #tsdId FROM tL JOIN tSE ON tL.idL = tSE.idSE WHERE tL.Selection=1 ", sqliteCon);
cmd2.Parameters.AddWithValue("#tsdId", generatedId);
cmd2.ExecuteNonQuery();
MessageBox.Show("Dato Aggiunto");
}
sqliteCon.Close();
1.1
SqlCommand cmdRD = new SqlCommand("SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1", sqliteCon);
var RD = cmdRD.ExecuteScalar();
var tot =pass;
using (cmdRD)
{
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
if(reader[0].ToString()==fail)
{
tot = fail;
break;
}
}
MessageBox.Show(tot);
}
}
i'm arrived to that(1.1) it works but i've to insert the TOT into RProva
Based on your question and comment I think you misunderstood ExecuteScalar:
ExecuteScalar executes the query, and returns the first column of the first row in the result set returned by the query. learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar
I dont know the Type of "RD" or "PASS", but the IF in your example (when using ExecuteScalar) seems OK. Else when you are using ExecuteReader you should use some kind of an loop to iterate through the Items. Like this:
string pass = "abc"; // guessing types and values
string fail = "failed";
string sqliteCon = "Data Source=(localdb)\\MSSQLLocalDB;Database=BooksDb";
using (SqlConnection connection = new SqlConnection(sqliteCon))
{
connection.Open();
var queryString = #"SELECT ResItem AS RD
FROM tSE
JOIN tL ON tSE.idSE = tL.idL
WHERE tL.Selection=1";
var values = new List<string>();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
var queryInsert = #"INSERT INTO tSD (NomeItem,ResItemDet,DateStartDet,DateEndDet)
VALUES (#NI, #RProva, #DATESE, #DATEED)";
using (SqlCommand command2 = new SqlCommand(queryInsert, connection))
{
foreach(var value in values)
{
command2.Parameters.Clear();
if (value.Equals(pass))
{
command2.Parameters.AddWithValue("#RProva", value);
}
else
{
command2.Parameters.AddWithValue("#RProva", fail);
}
command2.ExecuteNonQuery();
}
}
}
Theres for sure a better way, but maybe this helps you out.
EDIT:
Here is how I would implement your code example:
using (SqlConnection sqliteCon = new SqlConnection(connection))
{
sqliteCon.Open();
var values = new List<string>();
var query = "SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1";
using (SqlCommand cmdRD = new SqlCommand(query, sqliteCon))
{
var RD = cmdRD.ExecuteScalar();
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
int generatedId = 0;
var query2 = "INSERT INTO tSD(NomeItem,ResItemDet,DateStartDet,DateEndDet) OUTPUT inserted.Id VALUES (#NI,#RProva,#DATESE,#DATEED)";
using (SqlCommand cmd1 = new SqlCommand(query2, sqliteCon))
{
foreach (var value in values)
{
cmd1.Parameters.Clear();
cmd1.Parameters.AddWithValue("#DATESE", DATESE);
cmd1.Parameters.AddWithValue("#DATEED", DATEED);
cmd1.Parameters.AddWithValue("#NI", NI);
if (value.Equals(pass))
{
cmd1.Parameters.AddWithValue("#RProva", value);
}
else
{
cmd1.Parameters.AddWithValue("#RProva", fail);
}
cmd1.ExecuteNonQuery();
}
generatedId = Convert.ToInt32(cmd1.ExecuteScalar());
}
var query3 = "UPDATE tSE SET FK_TSD_id = #tsdId FROM tL JOIN tSE ON tL.idL = tSE.idSE WHERE tL.Selection=1 ";
using (SqlCommand cmd2 = new SqlCommand(query3, sqliteCon))
{
cmd2.Parameters.AddWithValue("#tsdId", generatedId);
cmd2.ExecuteNonQuery();
}
}
How to use Combobox.SelectedValue to construct WHERE clause?
conL.Open();
cmdL.Connection = conL;
cmdL.CommandText ="SELECT Id FROM dbAllServers WHERE Server_Names='" + cmb_SQLNames.SelectedValue +"'";
SQLiteDataReader r = cmdL.ExecuteReader();
while(r.Read())
{
serID = int.Parse(r[0].ToString());
MessageBox.Show("Current Selected Server ID is:..." + serID.ToString());
}
conL.Close();
An example of parameterized query, might be helpful:
string query = "SELECT Id FROM dbAllServers WHERE Server_Names=#server_name";
string serverName = cmb_SQLNames.SelectedValue;
using (SQLiteConnection connection = new SQLiteConnection(GetConnectionString()))
{
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
cmd.Parameters.Add(new SQLiteParameter("#server_name", serverName));
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// do your job here
}
}
}
}
I need to know how to get all the clientID that are #2 so i could get the programs they are assigned to...so far my code only gets the first clientID with #2 in it...
int progs;
string Command = #"select * from clientprogram where clientProgClientID = #clientID;";
using (MySqlConnection mConnection = new MySqlConnection(mycon))
{
mConnection.Open();
using (MySqlCommand cmd2 = new MySqlCommand(Command, mConnection))
{
cmd2.Parameters.Add(new MySqlParameter("#clientID", lblcID.Text));
using (MySqlDataReader reader = cmd2.ExecuteReader())
{
if (reader.Read())
{
progs = (int)reader["clientProgramID"];
cmbProgram.Items.Add(progs);
}
}
}
mConnection.Close();
}
Change
if (reader.Read())
to
while (reader.Read())
It seems it should be in a loop to add records recursively rather than just the first one
of course it only get the first result because you are reading it only once.
use while(reader.Read()) instead of if(reader.Read()).
while(reader.Read())
{
progs = (int)reader["clientProgramID"];
cmbProgram.Items.Add(progs);
}
change
if (reader.Read())
to
while(reader.Read())
side note; don't use select * when you only need single column data, use select Coumnname from yourtable
int progs;
string Command = #"select * from clientprogram where clientProgClientID = #clientID;";
using (MySqlConnection mConnection = new MySqlConnection(mycon))
{
mConnection.Open();
using (MySqlCommand cmd2 = new MySqlCommand(Command, mConnection))
{
cmd2.Parameters.Add(new MySqlParameter("#clientID", lblcID.Text));
using (MySqlDataReader reader = cmd2.ExecuteReader())
{
while (reader.Read()) // CHANGE TO THIS
{
progs = (int)reader["clientProgramID"];
cmbProgram.Items.Add(progs);
}
}
}
mConnection.Close();
}
Is it possible to select data from a table with a specific ID? I know it works for update but what is the code for the select?
Im using c# in visual studios, my goal is to display the details in readOnly textboxes.
string corp =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = CorpID.Text";
this should do it
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
corporateName.Text = dtResult.Rows[0]["corporateName"];
corporateAddress.Text = dtResult.Rows[0]["corporateAddress"];
corporateContact.Text = dtResult.Rows[0]["corporateContact"];
}
}
probably you should add some error handling and handle the case that CorpID doesn't exist
UPDATE another approach
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand cmd = new MySqlCommand(Command, mConnection))
{
cmd.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
corporateName.Text = (string)reader["corporateName"];
corporateAddress.Text = (string)reader["corporateAddress"];
corporateContact.Text = (string)reader["corporateContact"];
}
}
}
}
Yes, it is possible,
your sql string is OK, except last part, you will edit last part
string corp = "select corporateName, corporateAddress, corporateContact from corporatemembership where corporateID = " + "'" + CorpID.Text + "'";
I have a constructor that takes data from a SQL Server database and puts it in a local SQLite database:
public ForemanController()
{
connectionString.DataSource = "dxdb02v";
connectionString.InitialCatalog = "QTRAX4619410";
connectionString.UserID = "tunnelld";
connectionString.Password = "david";
string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";
List<Foreman> list;
// Creates a SQL connection
using (var connection = new SqlConnection(connectionString.ToString()))
{
using (var command = new SqlCommand(queryString, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
list = new List<Foreman>();
while (reader.Read())
{
list.Add(new Foreman { ForeBadge = reader.GetString(0), ForeName = reader.GetString(1) });
}
}
}
connection.Close();
allForeman = list.ToArray();
}
string deleteSQL = "DELETE FROM Foreman;";
using (SQLiteConnection SQLconn1 = new SQLiteConnection(SQLiteConnectionString))
{
using (var command = new SQLiteCommand(deleteSQL, SQLconn1))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
}
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
{
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
{
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (#param1, #param2);";
cmd2.Parameters.Add(new SQLiteParameter("#param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("#param2", row.ForeName));
cmd2.ExecuteNonQuery();
}
}
}
Everything seems to be working fine until the last using statement:
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
{
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
{
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (#param1, #param2);";
cmd2.Parameters.Add(new SQLiteParameter("#param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("#param2", row.ForeName));
cmd2.ExecuteNonQuery();
}
}
I'm getting this error:
That's because that's the only place you forgot to open the connection.
add this: SQLconn2.Open();
You forgot to open the connection.
SQLConn2.Open();