Update Query C# MySQL Forms - c#

Before you comment please note that I understand that my code is vulnerable to SQL injection, please disregard any comments about it being vulnerable for purposes of simplicity
I've checked around the website for answers but none seem to fit my situation, many are PHP.
I am trying to update information on a MySQL database from C# Forms Application on Visual Studio 2012, so I've allowed the user to input data but I want them to be able to update their data.
I've tried all sorts of different methods many give me errors, I feel like I'm very close with this method.
string Connection = "server = xxxx; " + "database = xxxxx; " + "uid = xxxx;"+ "pwd = xxxxx;";
MySqlConnection Conn = new MySqlConnection(Connection);
try
{
MySqlDataAdapter dAdapter = new MySqlDataAdapter("SELECT * FROM example", Conn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
DataRow dr = dTable.NewRow();
dr["TestData1"] = Convert.ToInt32(cboTestData1.Text);
dr["TestData2"] = txtTestData2.Text;
dr["TestData3"] = Convert.ToInt32(txtTestData3.Text);
dTable.Rows.Add(dr);
string Query = "Update example(field 1, field 2, field 3) VALUES ("TestData1", "TestData2", "TestData3")";
dTable.Rows.Add(Query);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dAdapter);
int iRowsAffected = dAdapter.Update(dTable);
if (iRowsAffected == 1)
{
MessageBox.Show("Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error adding record", "Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
The issue is that it doesn't like the 'Query' code due to it being bad. It gives me this error message
Additional information: Input string was not in a correct
format.Couldn't store in ID Column. Expected
type is Int32.
I've looked around the internet for solutions but all either do not offer the same situation as mine or are related to PHP code.

The update query should be in a syntax of...
update SomeTable
set SomeField = NewValue,
AnotherField = AnotherValue
where
SomeKey = KeyIDTheUserWasWorkingWith
Also, for future, I know this is sample mach-up data/columns, but you should really use real table / column names. The sample data, we know could be made up to prevent confidentiality, but real structures are more practical to get answers accurate.
The INSERT statement is closer to what you have and is ...
insert into SomeTable
( fld1, fld2, fld3 )
values
( someFld1, anotherFld2, lastField )
Finally, with your column names, if you DO (but I never do), have columns with embedded spaces, be sure to
`wrap in tic marks`
, so the engine recognizes the whole string as the column name.

I think there is some confusion in your code.
The SELECT statement may be bringing back 4 fields such as: ID, TestData1, TestData2, TestData3.
You then fill a DataTable with the records retrieved from the database.
Next, you create a new DataRow in the DataTable (that will have the four columns that match the SELECT statement). You place values into the editable fields (not the ID field).
Then you add the DataRow to the DataTable.
Here its where it gets mixed up...
You create a SQL Update Query String - then add that string as a DataRow to the DataTable.
When updating the DataTable via the MySqlDataAdapter, the last DataRow is not a valid record to be parsed by the Adapter.
Try removing the two lines:
string Query = "Update example(field 1, field 2, field 3) VALUES ("TestData1", "TestData2", "TestData3")";
dTable.Rows.Add(Query);

Related

Reading existing rows from a database using C#

The application I am developing is meant to be a quick and easy tool to import data to our main app. So the user loads in a CSV, meddles with the data a little and pushes it up to the database.
Before the data is pushed to the database, I have a verification check going on which basically says, "Does a customer exist in the database with the same name, account and sort codes? If so, put their guid (which is known already) into a list."
The problem is, the result variable is always 0; this is despite the fact that there is duplicate test data already in my database which should show a result. Added to that, using SQL Profiler, I can't see a query actually being executed against the database.
I'm sure that the ExecuteScalar() is what I should be doing, so my attention comes to the Parameters I'm adding to the SqlCommand... but I'll be blowed if I can figure it... any thoughts?
string connectionString = Generic.GetConnectionString("myDatabase");
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand check = new SqlCommand("select COUNT(*) from Customers C1 INNER JOIN CustomerBank B1 ON C1.Id = B1.CustomerId WHERE C1.Name = #Name AND B1.SortCode = #SortCode AND B1.AccountNumber = #AccountNumber", conn);
foreach (DataRow row in importedData.Rows)
{
check.Parameters.Clear();
check.Parameters.Add("#Name", SqlDbType.NVarChar).Value = row["Name"].ToString();
check.Parameters.Add("#SortCode", SqlDbType.NVarChar).Value = row["SortCode"].ToString();
check.Parameters.Add("#AccountNumber", SqlDbType.NVarChar).Value = row["AccountNumber"].ToString();
Object result = check.ExecuteScalar();
int count = (Int32)result;
if (count > 0)
{
DuplicateData.Add((Guid)row["BureauCustomerId"]);
}
}
}
Clarification: importedData is a DataTable of the user's data held in this C# application. During the ForEach loop, each row has various columns, a few of those being Name, SortCode and AccountNumber. The values seem to get set in the parameters (but will verify now).

Checking and Saving/Loading from MySQL C#

I am making something that requires MySQL. I have the saving done from in-game, which is simply done by INSERT.
I have a column that will have a password in and I need to check if the inputted password matched any of the rows and then if it is, get all of the contents of the row then save it to variables.
Does anyone have an idea how to do this in C#?
//////////////////////////
I have found how to save and get the string, however it will only get 1 string at a time :(
MySql.Data.MySqlClient.MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM (player) WHERE (pass)";
command.ExecuteNonQuery();
command.CommandType = System.Data.CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader reader = command.ExecuteReader();
reader.Read();
ayy = reader.GetString(1);
print (ayy);
if(ayy == password){
//something
}
My best practice is to use MySQLDataAdapter to fill a DataTable. You can then iterate through the rows and try to match the password.
Something like this;
DataTable dt = new DataTable();
using(MySQLDataAdapter adapter = new MySQLDataAdaper(query, connection))
{
adapter.Fill(dt);
}
foreach(DataRow row in dt.Rows)
{
//Supposing you stored your password in a stringfield in your database
if((row.Field<String>("columnName").Equals("password"))
{
//Do something with it
}
}
I hope this compiles since I typed this from my phone. You can find a nice explanation and example here.
However, if you are needing data from a specific user, why not specificly ask it from the database? Your query would be like;
SELECT * FROM usercolumn WHERE user_id = input_id AND pass = input_pass
Since I suppose every user is unique, you will now get the data from the specific user, meaning you should not have to check for passwords anymore.
For the SQL statement, you should be able to search your database as follows and get only the entry you need back from it.
"SELECT * FROM table_name WHERE column_name LIKE input_string"
If input_string contains any of the special characters for SQL string comparison (% and _, I believe) you'll just have to escape them which can be done quite simply with regex. As I said in the comments, it's been a while since I've done SQL, but there's plenty of resources online for perfecting that query.
This should then return the entire row, and if I'm thinking correctly you should be able to then put the entire row into an array of objects all at once, or simply read them string by string and convert to values as needed using one of the Convert methods, as found here: http://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx
Edit as per Prix's comment: Data entered into the MySQL table should not need conversion.
Example to get an integer:
string x = [...];
[...]
var y = Convert.ToInt32(x);
If you're able to get them into object arrays, that works as well.
object[] obj = [...];
[...]
var x0 = Convert.To[...](obj[0]);
var x1 = Convert.To[...](obj[1]);
Etcetera.

Can we use variable for a table name in query?

Here in the code I am trying to retrieve information from a database and store it in a table. In query i have used a variable to specify a table, i am doing so because i want to use this single piece of code to retrieve information from various tables based on which table name the variable "a" contain but when i am executing this it's throwing me an exception. please help...
MyOleDbConnection.Open();
string a = "login";
string query = string.Format("select Email,Username,PhoneNo,Department from '{1}' where Email='{0}'", editrecordtextBox.Text,a);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter(query, MyOleDbConnection.vcon);
da.Fill(dt);
Note- this is just the part of the code, the exception is occuring in this code only.
Your code is in fact working correctly.
First of all, remove your single quotes around the table name. These mark a text, not an identifier or name.
I can imagine that login is a reseverd name you cannot use as plain text in your SQL. Depending on the database you can quote your tablename so it is recognizes as a name, not an reserved word.
For SQL-Server it would be done with [ and ]:
string query = string.Format("select Email,Username,PhoneNo,Department from [{1}] where Email='{0}'", editrecordtextBox.Text,a);
If you would give us your database, we could help.
the way that tested and Worked is something like Below as you see the Table Name is Variable Form i Make a query with concatenate 3 section together
string query = "SELECT TOP 1 * FROM M" + TableName.ToString() + " ORDER BY ID
DESC";

GridView Table 1 related to Table 2

Sorry I know Title is really confusing but I couldn't figure out what exactly to put down.
Basically I created a Grid View which queries database and displays data. It works perfectly, no complain, however what I have right now is,
but what I want is,
Question: I am not sure how can I do this, can someone just point me out in right direction please ?
I think I will going to use nested gridviews.
Try to change your SELECT Query like below... It will you to get the Expected Result...
SQL Fiddle : http://www.sqlfiddle.com/#!3/00b5f/15
I have named the Table as Fruits
SELECT CrateTitle,CrateDescription,CrateID,
stuff(
(
SELECT ','+ [FruitTitle] FROM fruits WHERE CrateID = t.CrateID FOR XML path('')
),1,1,'') Types_of_Fruits_in_Crate
FROM (SELECT DISTINCT CrateTitle,CrateDescription,CrateID FROM fruits )t
OR
CREATE a PROC
*Place this Query in that Proc*
*Call that Proc*
*assign that Result set to GridView*
You can Assign he Stored Proc Result set to GridView by using the Below Code :
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("Your Connection String");
try
{
connection.Open();
string spName = "YOURStoredProcudureName";
SqlCommand sqlCmd = new SqlCommand(spName, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
//display the DataTable to a Data control like GridView for example
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
This is more an sql (or whatever langue your database engine uses) problem than a c# problem although one solution from c# would be (though it may be a bit of extra work) to use a html literal to draw you table at run time
the other option would be to change your sql but without more information i can't say if you could perhaps use a group by on changeID or a pivot table

DataGridView and Record ID C#

I guess I need some clarification on how the (My)SqlDataAdapter works. I have a DGV that I use to display one column from a MySQL table; however when I need to edit the record, I need most of the other fields and I do this in another winform. So I guess I need some best practices advice:
Question 1: When binding to the datasource: Do I need to select ALL the fields I want to edit in the form?
string query = "SELECT * FROM cusdata";
cusAdapter = new MySqlDataAdapter(query,pppDB.sqlConn);
cusAdapter.Fill(mainSet,"cusdata");
dgv_cusData.DataSource = mainSet.Tables["cusdata"]
Question 2: I see a lot of info all over the web about selecting just the fields you want to display in the DGV but if I edit that data how does the adapter know exactly what record is being updated on the back-end??
I guess I am just a bit confused about the different approaches and I need some guidance. I want a datagridview where I can display a single column (Customer Name). I want to be able to edit the customer record in another form and have the DVG refreshed with the new information upon successful completion of the Database action.
I have given the best part of a weekend through today to find an article or blog or something that demonstrates EXACTLY that. List-Form paradigm. Can someone please point me in the right direction? Thanks much to the community.
by experience you should not select all the fields, rather select only the fields you need
Select CustId, CustName, CustAddress, CustPhone from cusdata
this will impact performance.
when you edit a data you can use the code below:
string connectionString = "[Put your connection string here]";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE cusdata SET CustName=#CustName, CustAddress=#CustAddress WHERE CustId=#CustId", conn))
{
cmd.Parameters.AddWithValue("#CustId", 1);
cmd.Parameters.AddWithValue("#CustName", "Name Input");
cmd.Parameters.AddWithValue("#CustAddress", "Address input");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
this part of the code let you specify the fields and data you want to update in your table
cmd.Parameters.AddWithValue("#CustId", 1);
cmd.Parameters.AddWithValue("#CustName", "Name Input");
cmd.Parameters.AddWithValue("#CustAddress", "Address input");

Categories

Resources