1

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

1
  • remove single quote for a.Columns[1] Commented Feb 25, 2013 at 9:19

2 Answers 2

2

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()
            ...);
Sign up to request clarification or add additional context in comments.

Comments

1

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]+")"

1 Comment

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]+")"; MySqlCommand acmd=new MySqlCommand(); acmd.CommandText=query; acmd.Connection=con; acmd.ExecuteNonQuery(); con.Close();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.