Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to TRUNCATE table with C#

Tags:

c#

mysql

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.

like image 301
Oriol Lopez Avatar asked Feb 11 '23 00:02

Oriol Lopez


2 Answers

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

like image 178
Raj Avatar answered Feb 13 '23 03:02

Raj


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

dbContext.ExecuteCommand("TRUNCATE TABLE <tableName>");
like image 22
Gabriel Marius Popescu Avatar answered Feb 13 '23 03:02

Gabriel Marius Popescu