how to delete data in Sql Server 2012 using c#? - c#

i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?

Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article

Related

sqlite insert with c#

i am testing my sqlite local server with c#, I have the connection and query setup without problem. I tried to copy the query to sqlite and it runs without problem. However, when I run it in my program, nothing insert into the db. Wondering what the problem is.
I have set the db build action to Content, and the copy to output directory options to copy if newer
private void insertIntoDB(string query)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=.\\VHTDatabase.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
Console.WriteLine(query);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
Try a full path to your database in your Connectionstring
Then maybe try to add the CommandText before you open the Connection.
i mean:
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Does your database give you informations with SELECT?
Maybe you need to reconfigure the User of the Database and give him rights to write, change and delete.
If nothing helps, then you can check, if it gives you an error.
try
{
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}

Is this Sql injection proof Asp.net code?

Can somebody tell me the pros and cons of this code? I know I can use stored procedures instead, but would it be easy to SQL inject this code considering I had a textbox where admins could input the commentid?
string commentId = a.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString);
con.Open();
string sql = "DELETE FROM Comment WHERE Comment.commentId = #commentid";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#commentid", commentId);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Yes, it looks fine, since you're using paramterized sql. However, you haven't given your table an alias, so I thing your sql should be
DELETE FROM Comment WHERE commentId = #commentid
As well as protecting you from sql injection attacks, Sql Server will know that this sql may be called again with different parameters, so can cache an efficient execution plan for it.
As an aside, you should always dispose of connections after using them.
string commentId = a.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager
.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString))
{
con.Open();
string sql = "DELETE FROM Comment WHERE Comment.commentId = #commentid";
using(SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#commentid", commentId);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
As you can see, there is a fair amount of code for such a simple operation. You may wish to take a look at dapper, which will remove a lot of these issues. There are many libraries to help you, which are off-topic here, but its a lightweight, popular one
Pros:
Good thing is you are using parameters for command which is sql injection safe.
Cons:
Not well written.
Not using function for CRUD. Always Use functions to do CRUD operation.
No Use of Using block. Always use using block, so you don't need to dispose connection & command. You don't need to manually close it.
Use following code in DataAccessLayer.
public void DeleteComment(int commentId)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString))
{
con.Open();
string sql = "DELETE FROM Comment WHERE Comment.commentId = #commentid";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#commentid", commentId);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
You can write connection open code in separate function too.
Check this article for more detail:
https://www.codeproject.com/Articles/813965/Preventing-SQL-Injection-Attack-ASP-NET-Part-I

Rolling Back a SQL Server query

I found a few links regarding rolling back a SQL Server query but have had problems implementing it. Since the information I am inserting and updating needs to always be correct I need to make sure this is working beforehand. Now, I already have a try/catch block, and I know the rollback goes into the catch block. For example, this is my code:
using (SqlConnection conn5 = new SqlConnection(connString))
{
try
{
string query = "INSERT QUERY";
SqlCommand cmd = new SqlCommand(query, conn5);
// PARAMETERS
conn5.open();
cmd.ExecuteNonQuery();
}
catch
{
cmd.Rollback();
}
}
I tried cmd.RollBack() but it just blew in my face.
You open a transaction scope. It will automatically perform a rollback unless the Complete() method is called.
using (var tScope = new TransactionScope())
using (SqlConnection conn5 = new SqlConnection(connString))
{
string query = "INSERT QUERY";
SqlCommand cmd = new SqlCommand(query, conn5);
PARAMETERS
conn5.open();
cmd.ExecuteNonQuery();
// If an exception is thrown, the call to Complete() will never be reached and the
// changes will be rolled back.
tScope.Complete();
}

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Microsoft Access OleDb Connection Error

I am trying to access an Access 2003 database remotely from my ASP.NET application. My code is:
DataSet dsImportedData = new DataSet();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=MS Remote;Remote Provider=Microsoft.Jet.OLEDB.4.0;Remote Server=http://myIp;Data source=C:\myDatabase.mdb;";
try
{
System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command);
adapter.Fill(dsImportedData);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
However, I am always getting an exception stating: {"[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."}
My command is basic, I have no idea what could be wrong with it. Did anyone confront with the same issue? Thanks!
Try this ....
String command = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command, conn);
adapter.Fill(dsImportedData);
Apparently the error can be caused by the specified table not existing. Just a thought...
Another thought would be to remove the remoting complexity and try to get to the most simple working code, possibly with a new access database just to start to narrow down what is causing the problem.
If you set the command type to Stores procedure it works for me.
command.CommandType = System.Data.CommandType.StoredProcedure;

Categories