Oriol Lopez
Oriol Lopez

Reputation: 369

How to TRUNCATE table with C#

How I can truncate a table with c#.

I do this but it doesn't work.

cmd.CommandText = "TRUNCATE TABLE dalbara;";
cmd.ExecuteNonQuery();

Visual Studio give me this error:

Invalid SQL command, you only can do 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT' or 'UPDATE'

I want to delete and restart all of my access table. With the DELETE command, the autoincrement values, doesn't reset.

Upvotes: 5

Views: 32177

Answers (4)

Gabriel Marius Popescu
Gabriel Marius Popescu

Reputation: 2186

If you're some sort of database context you can do this:

dbContext.ExecuteCommand("TRUNCATE TABLE <tableName>");

Upvotes: 2

Raj
Raj

Reputation: 143

REVOKE ALL PRIVILEGES ON * . * FROM  'root'@'localhost';

GRANT ALL PRIVILEGES ON * . * TO  'root'@'localhost' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

Change your host name and username, execute in your server and run your truncate c# code.

Upvotes: 0

Raj
Raj

Reputation: 143

In MySQL Go -> Home ->Users menu-> select User in table ->Edit Privileges->Check All Global privileges -> Go

Now execute truncate code.

Upvotes: 0

Raj
Raj

Reputation: 143

MySqlConnection connection = new MySqlConnection(Server=localhost;Database=dbase;Uid=root;password=;)    
string query = "TRUNCATE TABLE " + yourTableName
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();

Use this code to truncate table

Upvotes: 8

Related Questions