C# SQL : update with params - getting 0 and without the text - c#

I am making DatabaseManager class for my solution and I am getting the number 0 when I am trying to update the text.
For example : I have now the name michael and I wanted to change it to "michael , mike" so I'll probably use update.
public void AddCrime(CSteamID id, string crime, string time)
{
try
{
MySqlConnection connection = createConnection();
MySqlCommand command = connection.CreateCommand();
crime = "," + crime;
command.CommandText = "update `" + Main.Instance.Configuration.Instance.DatabaseTableName
+ "` set `crime` = crime + ( #crime ) where `steamId` = #steamID; select `crime` from `"
+ Main.Instance.Configuration.Instance.DatabaseTableName
+ "` where `steamId` = #steamID";
command.Parameters.AddWithValue("#steamID", id);
command.Parameters.AddWithValue("#crime", crime);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
AddTime(id, time);
}
catch (Exception ex) { Logger.Log(ex); }
}
How do I call it :
DatabaseManager.AddWanted(player.CSteamID, command[1], command[2]);
Thanks everyone!

yor last sentence in your command is a select statement, NonQuery does not return values, only the number of rows affected. Change it to ExecuteScalar and store the value of the select in a variable.
Second error is the data type of the parameter #steamID. You set the value id, which is declares as CSteamID id... CStreamId is not string, change the AddWithValue

Fixed, I added another method to get crime from table and then changed the void crime string to the current string + the table text.
The error was : Truncated incorrect DOUBLE value.

Related

Using C# SqlCommand to Query SQL Table

I have a class SqlGetGroupCutRates which has a
public bool UpdateDefaultTarget(string param1)
method. In this method, I am using the SqlClient.SqlCommand class.
public bool UpdateDefaultTarget(string g1)
{
string myworkCenterCode = Form1.globalWorkCenter;
try
{
string connString = #"Data Source =" + server + "; Initial Catalog =" + redGreenDB + ";Integrated Security=SSPI";
// WHERE CUT_RATE_GROUP = #CUT_RATE_GROUP... WHAT IS #CUT_RATE_GROUP????
string myCommandString = "SELECT TOP 1 Default_Cut_Rate_Per_Hour FROM " + groupCutRateTable + " WHERE " +
"Cut_Rate_Group= #Cut_Rate_Group ORDER BY Record_Date DESC";
// SQL connection using the connString taking us to the redGreenDB
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Get the specific default cut rate from groupCutRateTable ("dbo.ABR_Tape_Cvt_Group_Cut_Rates") where Cut_Rate_Group (column)
using (SqlCommand cmd = new SqlCommand(myCommandString, conn))
{
cmd.Parameters.AddWithValue("Cut_Rate_Group", g1);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
defaultFoundInQuery = true;
while (reader.Read())
{
int ordTarget = reader.GetOrdinal("Default_Cut_Rate_Per_Hour");
// Handle potential null database values:
if (!reader.IsDBNull(ordTarget))
{
int ord1 = reader.GetOrdinal("Default_Cut_Rate_Per_Hour");
default_Cut_Rate_Per_Hour = reader.GetDouble(ord1);
}
else
{
default_Cut_Rate_Per_Hour = 0;
}
}
}
// else if no data rows found.
else
{
default_Cut_Rate_Per_Hour = 0;
}
conn.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem getting Group Cut Rates from database: \n" + ex);
}
return defaultFoundInQuery;
}
In my myCommandString variable, you will notice it is set to the value
string myCommandString = "SELECT TOP 1 Default_Cut_Rate_Per_Hour FROM " + groupCutRateTable + " WHERE " +
"Cut_Rate_Group= #Cut_Rate_Group ORDER BY Record_Date DESC";
I am querying the top 1/first Default_Cut_Rate_Per_Hour column value from the groupCutRateTable WHERE the Cut_Rate_Group column value is #Cut_Rate_Group.
My question is... in this query... what is meant by the #Cut_Rate_Group part of the query? Is this just going to return the first Cut_Rate_Group column value? Essentially making this a "static" query that will always return the same value? Or is the syntax of #Cut_Rate_Group seen as dynamic? Meaning #Cut_Rate_Group is assigned a value somewhere in my code?
Apologies, I am very new to this. If you have any docs I could read further into this, I would also appreciate that so I can better understand any answer I may get. Thanks for taking the time to read this.
I am expecting that this syntax would make #Cut_Rate_Group dynamic in the sense that it is almost viewed as a variable that is assigned a value.
The statement
cmd.Parameters.AddWithValue("Cut_Rate_Group", g1)
creates the parameter #Cut_Rate_Group that is referred to in the select statement. Since its value comes from the parameter g1, it will be "dynamic" in that whatever value is passed in g1 will become the value of the parameter #Cut_Rate_Group used in the select statement.
The statement above could have been written
cmd.Parameters.AddWithValue("#Cut_Rate_Group", g1)
If you call UpdateDefaultTarget with the same value of g1, and no records have been deleted from the table, it will return the same record if no new records have a record date less than or equal to that original record.
However, not knowing what you are trying to accomplish, this may not be what you actual want to happen.
#Cut_Rate_Group is a sql paramter (and is dynamic like a variable). Parameterization of sql commands is to safe guard from sql injections.
It's value is added here
cmd.Parameters.AddWithValue("Cut_Rate_Group", g1)

Parameterized query not working in C#

I am currently in a corner and have no idea why the following code will not execute properly and update the database (Access).
newUser = All of the new user's data including their ID
list = Contains a list of GermanResources (class) entries that correspond to the pages checkboxes. Class includes .Name (text value of checkbox) and .Value (checked? 1 or 0)
I want to update the database with the checkbox value of each GermanResource.
IF i replace #acc_Value with the value 1 this code works. It seems to not work with the first parameter in place. Debugging this showed me that everything had the proper values at the proper times and since "1" worked I know the data types are not mismatched.
Note: There were no errors with or without the parameter in place.
I would appreciate any input about this.
This is one of the CommandTexts that are generated:
UPDATE VMS_GRM_GermanResource_Access SET VTOFZN = #acc_Value WHERE UserId = #userId
private bool NewUser_Insert_GermanResourceAccess(OleDbConnection connection, User newUser, List<GermanResource> list)
{
bool result = false;
try
{
foreach (var item in list)
{
string column = item.Name.Replace(" ", "");
string query = #"UPDATE VMS_GRM_GermanResource_Access SET " + column + " = #acc_Value WHERE UserId = #userId";
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#userId", newUser.Id);
command.Parameters.Add(new OleDbParameter("#acc_Value", OleDbType.Integer, 1));
command.Parameters["#acc_Value"].Value = item.Access;
command.ExecuteNonQuery();
}
result = true;
}
catch (OleDbException ex)
{
UADConnection.Close();
MessageBox.Show(ex.ErrorCode.ToString() + ": " + ex.Message);
return result;
}
return result;
}
Use this to prepare sql statement :-
string query = #"UPDATE VMS_GRM_GermanResource_Access SET column_name=" +
#acc_Value + " WHERE UserId = " +#userId+";
#Tetsuya Yamamoto:
OLEDB parameters were not in order according to the query. Swapping them around to match the order in the query set things straight. All good again and thanks for everyone's inputs.

Getting a String from a value in Mysql in C#

i have the following table in MySql :
ID Name
1 Google
2 Yahoo
3 Facebook
4 Whatever
I have a textfield that when someone writes something and presses a button it stores this value in a string. This string is the Name of the above table. Then i have my code about selecting the id referred to that name. Ex, if the user enters Facebook i will find that the ID = 3. this is the code :
public bool FindCompanyID(string companyName)
{
return ExecQuery("select id from companies where name=#name",
cmd =>
{
cmd.CommandText = "SELECT id from companies WHERE name ='" + companyName + "'";
return cmd;
});
}
I want someone to show me a sample of code about the following : Saving to a string the " id " . if the ID in the database = 2 i want to make a
int Company_Number_ID
that i will use. How can i get the string to read the specified value from the database?
I am guessing your return type is bool to check whether the DDL statements were executed successfully.
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from companies WHERE name ='" + companyName + "'";
try
{
dbConn.Open();
Company_Number_ID = (Int32)cmd.ExecuteScalar();
} catch (Exception e) {
//Exception occured. Handle it here
}
Note: cmd.Parameters.AddWithValue("#companyName",companyName).
this is more secure
Edit: As pointed out in the comment by user3185569 , ExecuteScalar is better if you are sure it'll return only one row. But since no such information was provided. I did not consider that.
You can use ExecuteScalar directly like this.
Company_Number_ID = (Int32)cmd.ExecuteScalar();

SQL Syntax error in C# string

I'm running a query from a web form to update records. Since I'm just learning about C#, I'm using a command string as opposed to a stored procedure.
My update method is as follows:
public void updateOne()
{
string commandText = "update INVOICE SET <Redacted> = #<Redacted>,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
<needed a line break here, which is why I split the string again>
+ "WHERE K_INVOICE = #K_INV";
using (SqlConnection dbConnection = new SqlConnection
(conParams.connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, dbConnection);
cmd.Parameters.Add("#K_INV", SqlDbType.Int);
cmd.Parameters["#K_INV"].Value = #K_INV;
cmd.Parameters.AddWithValue("#<Redacted>", #<Redacted>.ToString());
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
cmd.Parameters.AddWithValue("#SupN", #SupN.ToString());
cmd.Parameters.AddWithValue("#Net", #Net.ToString());
cmd.Parameters.AddWithValue("VAT", #VAT.ToString());
cmd.Parameters.AddWithValue("#InvDt", #InvDt.ToString());
try
{
dbConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
errorString = e.Message.ToString();
}
}
}
Catch stalls on an SQL error (Incorrect syntax near SET), and I have an idea that the issue occurs because I convert the parameters to strings. The first parameter is an Int, which should be OK.
If this is the case, what should I convert the parameters to? If not, what on earth is wrong?
Try to add a # before the string to escape the breaklines, for sample:
string commandText = #"update INVOICE SET [Redacted] = #Redacted,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
+ "WHERE K_INVOICE = #K_INV";
In parameterName argument you can add the # but the value not, just the variable, for sample
cmd.Parameters.AddWithValue("#Redacted", redacted.ToString());
Try to execute this query in the databse with some values to check if everything is correct. You could use [brackets] in the table name and column names if you have a reserved word.
I would recommend you read this blog article on the dangers of .AddWithValue():
Can we stop using AddWithValue already?
Instead of
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
you should use
cmd.Parameters.Add("#Sup", SqlDbType.VarChar, 50).Value = ...(provide value here)..;
(is your variable in C# really called #SupN ?? Rather unusual and confusing....)
I would recommend to always define an explicit length for any string parameters you define

First code in c#

I'm very new in C#. I've written a small code. Can you help me with it :
Here is my code :
private void button1_Click(object sender, EventArgs e)
{
string povezava = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Matic\\Documents\\FERI\\2.LETNIK\\1.SEMESTER\\RPS\\VAJA3\\bazaPodatkov.accdb";
string zapisi = "update Zaposleni set ID='" + this.textBox1.Text +
"',Ime='" + this.textBox2.Text +
"',Priimek='" + this.textBox3.Text +
"',Uporabnisko_ime='" + this.textBox4.Text +
"',Geslo='" + this.textBox5.Text +
"',E_posta='" + this.textBox6.Text +
"',Ulica='" + this.textBox7.Text +
"',Hisna_stevilka='" + this.textBox8.Text +
"',Mesto='" + this.textBox9.Text +
"',Delovno_mesto='" + this.textBox10.Text +
"' where ID='" + this.textBox1.Text + "';";
OleDbConnection baza = new OleDbConnection(povezava);
OleDbCommand beri = new OleDbCommand(zapisi, baza);
OleDbDataReader branje;
try
{
baza.Open();
branje = beri.ExecuteReader();
MessageBox.Show("Podatki so shranjeni.");
while (branje.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm having a datatype mismatch in criteria expression.
Do you see anything wrong in my code ?
You code contains some visible errors and probably some invisible errors.
First problem.
Never do a string concatenation to build sql queries. Use always a parameterized query.
You put placeholders (? for OleDb/Access) where you want to put the values and then build a collection of parameters where you set the values. It is the framework code that substitutes the placeholders with the parameter's values putting the appropriate quotes around the values and removing the possibility of sql injection attacks (Little Bobby Tables).
Second, you have an update query, then there is no sense in returning an OleDbDataReader.
Just execute the command (by calling ExecuteNonQuery) and eventually check if the query updates any rows.
Third, enclose the OleDbConnection/Command with the using statement to ensure proper closing and cleanup of the connection and the command.
private void button1_Click(object sender, EventArgs e)
{
string povezava = "........."
string zapisi = "update Zaposleni set ID=?,Ime=?,Priimek=?,Uporabnisko_ime=?,Geslo=?," +
"E_posta=?,Ulica=?,Hisna_stevilka=?,Mesto=?,Delovno_mesto=? " +
"where ID=?";
try
{
using(OleDbConnection baza = new OleDbConnection(povezava))
using(OleDbCommand beri = new OleDbCommand(zapisi, baza))
{
baza.Open();
beri.Parameters.AddWithValue("#p1",this.textBox1.Text);
beri.Parameters.AddWithValue("#p2",this.textBox2.Text);
beri.Parameters.AddWithValue("#p3",this.textBox3.Text);
.... and so on for the other parameters
beri.Parameters.AddWithValue("#p11",this.textBox1.Text);
int rowsAffected = beri.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Finally, the invisible errors. You pass all of your values as strings. This is correct only if the database fields that receive the values are text fields. If one or more of your fields is not a string, (for example a date or an integer) then trying to set its value to a string triggers the datatype mismatch in criteria expression error message.
If this is the case then you need to convert the string to the appropriate datatype.
For example (assuming that the ID field is a numeric field)
beri.Parameters.AddWithValue("#p1",Convert.ToInt32(this.textBox1.Text));
You have one extra semicolon end of your command string (zapisi) delete it and try again.
Also consider using parameterized queries

Categories