How can i create a Table for MySql Database with C# - c#

My Question is how can i create a table with a table name what the user typed in? So i have already that:
string createtable = "CREATE TABLE '" + email.Text + "' (benutzung VARCHAR (20), passwort VARCHAR (30), id INTEGER);"; but everytime i start the program and try it again this error pops up:
MySql.Data.MySqlClient.MySqlException: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' (benutzung VARCHAR (20), passwort VARCHAR (30), id INTEGER)' at line 1"

I found the Solution from myself, what you must do is easily make it like that:
string createtable = "CREATE TABLE " + email.Text + " (benutzung VARCHAR (20),
passwort VARCHAR (30), id INTEGER);";
Now all works :D

Related

Conversion failed when converting the varchar value 'Batsman' to data type int

This is my C# code - I am running the query
INSERT INTO PM
VALUES ('Ali', '6777777', '3', 'Batsman', 'Fine Player', 'njhuh8obj', 'Lahore');
It is running fine in the database, but not this.
protected void btnAdd_Click(object sender, EventArgs e)//button that add players
{
// for picture to be uploaded
string path = "~/Admin/Players" FileUploadPicture.FileName;
FileUploadPicture.SaveAs(Server.MapPath(path));
SqlCommand cmd = new SqlCommand("INSERT INTO PM VALUES ( '" + TxtPlayerName.Text + "','"+TxtPlayerType.Text + "','" + TxtPlayerBasePrice.Text + "','" + TxtPlayerRecord.Text + "',
'" + ddlCat.SelectedItem.Value + "','" + path + "','" + TxtPlayerAddress.Text + "')", con);//Query of my C# page
// open connection with database
con.Open();
// Command for running query
cmd.ExecuteNonQuery();
con.Close();
// message shown after player is added
Response.Write("<script>alert('**Player Added**')</script>");
}
It seems that there is a problem in code of my C# page not in database, but I am not sure about that.
So please help me to solve this out...
It looks like the second column of your database table accepts an integer value but you are passing a string (TxtPlayerType.Text). If you want to insert an entry with only values for select columns you must specify the column names as follows:
INSERT INTO table_name (Column1, Column2, ...) VALUES (Value1, Value2, ...)
When Column Names aren't specified you must pass values in the order they appear in the database table.
Insert statement should follow the below format
Insert into <TableName>(Column1,Column2) Values (Value1,Value2)
It is good practice to define the column names in the statement as it make sure the order of the columns and also in future if new column added or deleted no need to change the code

create table in a specific schema through c# in mysql

I am trying to create a database and table in mySQL using C#. So far I can create a Schema in mysql through c#, but having trouble with creating table in that created schema.
User will enter the name of the schema to be created and then will enter the table name which will be created under the schema name entered before. Schema name and table names are taken in textbox values.
I am getting an error in table query the error is about syntax.
myQuery1.AppendFormat("CREATE SCHEMA {0}", databasenametxt.Text);
myQuery2.AppendFormat("CREATE TABLE {0} (name VARCHAR(20)) WHERE
database={0}",tblenametxt.Text,databasenametxt.Text);
string s1 = myQuery1.ToString();
string s2 = myQuery2.ToString();
MySqlCommand cmd = new MySqlCommand(s1, coat);
MySqlCommand cmd1 = new MySqlCommand(s2, coat);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
myQuery1 is executed successfully and a schema is created with the name entered in databasenametxt.Text but in myquery2 I am getting error.
The way I understand it is that you want to dynamically create a schema and tables in it. I am not sure of the error you get, but try using the following query:
CREATE TABLE schema_name.table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
For replacing the schema_name and table_name, it should work like following:
myQuery2.AppendFormat("CREATE TABLE {schema_name}.{table_name} ( {column_name1} {data_type}, .... ), your_schema_name, your_table_name, column_name1, data_type1);
You can also just add strings:
myQuery2.AppendFormat("CREATE TABLE " + your_schema_name + "." + your_table_name + " ( " + column_name1 + " " + data_type1 + ")");
It is just that you are creating a query string, which would run on sql server.
Also, you can get all the msql syntax for creating a table at https://dev.mysql.com/doc/refman/8.0/en/create-table.html
Let me know if it helps!
As pointed out in comment the error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE database=databasename' at line 1'"
is because "where database = .." is not valid syntax.
As schema is just a synonym for database in mysql you want
create database {0}
use {0}
create table {0} (`name` VARCHAR(20))
in each of your strings. Why the change to name? its a reserved word.

How to add one double-quotes (") to string?

I writing a request in C# for MySql Database and I need to write in string of the command double-quotes.
Something like:
String command ="Insert into table (column) values ("" + textBox1.Text + "")";
But I have a syntax error of C#. When I try chenge " to `
String command ="Insert into table (column) values ('" + textBox1.Text + "')";
I have a syntax error of Mysql(1054). Row column has a type varchar. How to correctly write this request in a program?
This is how:
string mystring = "We use \"a laser\"";
BUT! Since you are trying to form an sql query, you shouldn't do this yourself. You need to use sql parameters that will protect you from sql injection.
Here is a short lesson about sql parameters: http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

C# Alter Table and Add a column programmatically ASP.Net & SQL Server

I have been trying to add a column programmatically in ASP.NET to modify the tables in SQL Server.
Please see the following code:
string suppliernotxt = supplieridlist[1].ToString();
//SqlCommand cmd2 = new SqlCommand("ALTER TABLE [ProductNormalDB] ADD suppliernotxt nvarchar(20) NULL", con);
SqlCommand cmd2 = new SqlCommand("ALTER TABLE ProductNormalDB ADD #supplierlist nvarchar(20) NULL", con);
cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt);
//cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt.ToString());
//cmd2.Parameters["#supplierlist"].Value = supplieridlist[x];
cmd2.ExecuteNonQuery();
supplieridlist is an array that acquires all the column names to add into the SQL Server database. For some reason the parametrized method is not working and shows the following error:
Incorrect syntax near '#supplierlist'.
The basic idea is to have a user select from a check box the name of the suppliers, based on the selected number of suppliers the array will create the supplier names for ex. if we selected 3 suppliers, the array will save "Supplier1", "Supplier2", "Supplier3" and then the SqlCommand is supposed to alter the table and add the new columns.
You cannot use parameters to express the name of columns.
Parameters could only be used to express values for WHERE clause or for INSERT or UPDATE statements.
You could use string concatenation for your query text, passing the string value to a stored procedure or use some form of dynamic sql.
Please be very carefull with these kind of approaches because if you don't keep absolute control on the values passed to your code you will be exposed to Sql Injection.
Adding as an example of Dynamic SQL execution, but still vulnerable to SQL Injection
string suppliernotxt = supplieridlist[1].ToString();
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = '" + suppliernotxt + "'; " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"
SqlCommand cmd2 = new SqlCommand(execSQL, con);
cmd2.ExecuteNonQuery();
As you can see, even with Dynamic SQL there is nothing that prevent an SQL Injection attack passing via the suppliernotxt variable
EDIT As explained in the comments below from #RBarryYoung, a good improvement on the SQL Injection problem for this case of dynamic sql could be the usage of the QUOTENAME function to obtain an Unicode string with the required delimiters around the input string
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = QUOTENAME('" + suppliernotxt + "'); " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"

how to write mysql create table query in c#

how to create table query in c# for mysql database..
MySqlConnection con = new MySqlConnection("Server=localhost;Database=demo_test;UID=root;Password= ");
MySqlCommand acmd = new MySqlCommand("CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment,'" + a.Columns[1].ToString() + "' varchar(100) NOT NULL default,PRIMARY KEY (" + a.Columns[0]+") 1", con);
con.Open();
acmd.ExecuteNonQuery();
it gives me an error
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''name' varchar(100) NOT NULL default,PRIMARY KEY (id) 1' at line
1
Instead of fighting with SQL directly, you could use Mig# like this:
var schema = new DbSchema(ConnectionString, DbPlatform.MySql5);
schema.Alter(db => db.CreateTable("first")
.WithPrimaryKeyColumn(a.Colunns[0], DbType.Int32).AsIdentity()
...);
It's because you are wrapping the column names with single quote which converts the value into string and not an identifier anymore. Remove the single quotes and it will work.
string query = #"CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment, "
+ a.Columns[1].ToString() + " varchar(100) NOT NULL default,
PRIMARY KEY (" + a.Columns[0]+")"

Categories

Resources