Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Using a variable in a mysql command?

Hey Guys,

So I'm creating a small application that I could use some help with. I want my C# app to connect to a database and then run a command with the values that a user enters. Look at the below example:


A guys name is John Smith and he's 35. In the application I've set let's say string name=namebox.text or whatever as well as done the same for age. How would I run a create command on mysql or update a mysql command using the variables?

Like so:

INSERT INTO mydb (name, age) VALUES(name, age);

Or

Select * from mydb (name,age) where age = "age";

By "age" I of course mean the user inputted age, The problem is mysql requires the "" around the value and vb will attempt to recognize it as a literal text command. Any help is appreciated. Thanks!
You could just use simple string concatenation.
I.E.
Code
string query = "INSERT INTO mydb (name, age) VALUES('" +name + "'," + age + "");
or
Code
string query = "Select * from mydb (name,age) where age = " + age + "";

Then you would just use the query for the sql command.

Take note of the single quotes around the variables. Here I assumed that age is an integer field in the database.

Hope this helps ✌
(Jun 4, 2015 08:41 PM)HighARc Wrote:  You could just use simple string concatenation.
I.E.
Code
string query = "INSERT INTO mydb (name, age) VALUES('" +name + "'," + age + "");
or
Code
string query = "Select * from mydb (name,age) where age = " + age + "";

Then you would just use the query for the sql command.

Take note of the single quotes around the variables. Here I assumed that age is an integer field in the database.

Hope this helps ✌

That looks great, thanks so much man!
(Jun 4, 2015 08:41 PM)HighARc Wrote:  You could just use simple string concatenation.
Code
string query = "INSERT INTO mydb (name, age) VALUES('" +name + "'," + age + "");

... and you could use string.Format

Code
var query = string.Format("INSERT INTO mydb(name, age) VALUES ('{0}', {1})", name, age);
slowly becoming less active, contact me on-site before dealing.
Or, even better, you could all stop being stupid and suggest named parameters. Named parameters mean that you're never at fault for SQL injection, and it also makes your code look mighty cleaner. eg.

SqlCommand command = new SqlCommand("INSERT INTO mydb (name, age) VALUES (@name, @age);");

command.Parameters.AddWithValue("@name", "somenamehere");
command.Parameters.AddWithValue("@age", "someagehere");


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Shell] by ImDeepWithWindowsJul 4, 2020 06:19 PM 0 167 Jul 4, 2020 06:19 PM
Last Post: ImDeepWithWindows
[Shell] by friiz1337May 14, 2020 04:09 AM 2 207 May 14, 2020 04:09 AM
Last Post: sed-i
[Python] by SkidyMar 20, 2017 11:48 PM 6 259 Mar 20, 2017 11:48 PM
Last Post: obby