I'm trying to solve why my code isn't working. Tip is preciated. I'm also wondering, when this works, will the Primary key, in this case, the ID columns also reset and start all over from 1?
connection = new SqlConnection(connectionString);
connection.Open();
sql = "DELETE * From Guests";
sqlCommand = new SqlCommand(sql, connection);
sqlCommand.EndExecuteNonQuery();
connection.Close();
You don't need the asterisk
DELETE FROM Guests
To reset the primary key, use
TRUNCATE TABLE Guests
And you want
sqlCommand.ExecuteNonQuery();
not EndExecuteNonQuery
You don't need the "*". The correct syntax for a delete statement is:
delete from Guests
You should also get into the habit of using "using" for disposable types, like SqlConnection and SqlCommand. Like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "DELETE From Guests";
using (SqlCommand sqlCommand = new SqlCommand(sql, connection))
{
sqlCommand.ExecuteNonQuery();
}
}
Related
I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx
I want to create a table at the runtime and store information into it.
Below the code which i tried.
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String crt = "CREATE TABLE trail (Name Varchar(50) NOT NULL, Sex Varchar(50) NOT NULL)";
SqlCommand cov = new SqlCommand(crt, con);
cov.ExecuteReader();
String add = "Insert into trail value (#nam,#sex)";
SqlCommand cmd = new SqlCommand(add,con);
cmd.Parameters.AddWithValue("#nam",TextBox1.Text);
cmd.Parameters.AddWithValue("#sex", RbtGender.SelectedValue);
cmd.ExecuteReader();
con.Close();
Response.Redirect("Success.aspx");
There is no point to use ExecuteReader with CREATE statement. It does not return any data anyway (and it retursn SqlDataReader, it is not a void method). Use ExecuteNonQuery instead to execute your queries. Same with INSERT statement also.
And it is values not value. Take a look at INSERT (Transact-SQL) syntax.
Also use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cov = con.CreateCommand())
{
//
}
Don't use AddWithValue by the way. Use one of Add overloads. This method has some problems.
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
I wrote this code before
cmd.Connection = con;
Then I wrote this
cmd.ExecuteReader();
C# visual studio 2012 professional asp.net
I have a table containing usernames: Josh, Jeremy, Jared, Justin...
And I created a web page gridview that shows the entire table but I only want it to show Justin and nothing else.
How do I do this?
Here's some code that didn't work:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataReader rs;
con.Open();
SqlParameter uName = new SqlParameter("paramFName", Account.Text);
cmd.Parameters.Add(uName);
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
rs = cmd.ExecuteReader();
cmd.Parameters.Clear();
rs.Close();
Am I supposed to create a view of the table? I tried but wasn't successful.
tips?
You simply missed the "#" at the parameter name:
SqlParameter uName = new SqlParameter("#paramFName", Account.Text);
In case of your where-clause this has the effect that you didn't provide anything for the specified parameter which simply let the query provider ignore this condition, which results in the effective query SELECT * FROM Transactions.
Beside you should think about using the using block:
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
cmd.Parameters.AddWithValue("#paramFName", Account.Text);
con.Open();
using (var rs = cmd.ExecuteReader())
{
//ToDo: Do something with the reader.
}
}
And another hint: If you need to fill up a DataTable with the result, you can use a SqlDataAdapter instead of using the data reader:
using (var adapter = new SqlDataAdapter(cmd))
{
var dataTable = new DataTable();
dataTable.TableName = "QueryResult";
adapter.Fill(dataTable);
return dataTable;
}
If you are trying to select the first 10 names for example then you need to change your SQL Select to the following:
cmd.CommandText = "SELECT TOP 10 * FROM Transactions WHERE FName=#paramFName";
Is that what you were after?
EDIT
OK so you are not actually displaying your data anywhere which is the actual problem.
You need to create a datatable and display it in a gridview.
Check out the following links for examples:
Gridview examples
MSDN Gridview examples
Your code seems fine, although you do not provide much information.
If you're using SQL Server 2012 have a look at the keywords OFFSET and FETCH.
For earlier versions you need to use ROW_NUMBER OVER PARTITION
As a good practice you should always limit the number of elements returned.
I'm using the following code to clear a database table:
public void ClearAll()
{
SqlCommand info = new SqlCommand();
info.Connection = con;
info.CommandType = CommandType.Text;
info.CommandText = "edit_.Clear()";
}
Why does it not work?
With a sql command you usually pass a TSQL statement to execute. Try something more like,
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM Edit_ ";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You need to execute the command, so info.Execute() or info.ExecuteNonQuery().
Try info.CommandText='DELETE FROM edit_';
The CommandText attribute is the TSQL statement(s) that are run.
You also need a info.ExecuteNonQuery();
1) Decide whether to use a TRUNCATE or a DELETE statement
Use TRUNCATE to reset the table with all its records and indexes:
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "TRUNCATE TABLE [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Use DELETE to delete all records but do not reset identity/auto increment columns
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Note that there is another line in the samples. In the sample you provided the SQL statement never gets executed until you call one of the ExecuteXXX() methods like ExecuteNonQuery().
2) Make sure you use the correct object (are you sure its called edit_?). I recommend to put the schema before the table name as in the examples before.
3) Make sure you use the correct connection string. Maybe everything worked fine on the production environment ;-)
I've been trying to use the same SqlConnection and SqlCommand objects to execute to different commands.
the first one checks for duplicate and the second one inserts the data if the data the user entered is not a duplicate.
Here's a sample of my code:
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = #Name";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
comm.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar, 20);
comm.Parameters["#Name"].Value = Name;
comm.Parameters.Add("#IsVisible", System.Data.SqlDbType.Bit);
comm.Parameters["#IsVisible"].Value = IsVisible;
conn.Open();
if (comm.ExecuteScalar() == null)
{
Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (#Name, #IsVisible);";
comm.ExecuteNonQuery();
}
}
I was trying to save a trip to the database by using one connection.
The Problem is:
The first command runs okay but the
second command which inserts into the
database won't work (it doesn't add
any records to the db) and when I
tried to display the rows affected it
gave me -1 !!
The Question is:
Is this is the ideal way to check for
a duplicate records to constraint a
unique country ? and why the second
command is not executing ?
You are changing the value of string Command, but you are never actually changing the command string in SqlCommand comm.
When you rewrite the Command variable with the insert statement, you are simply modifying the string named Command that you've defined earlier. You are not modifying the command text stored inside of the SqlCommand object.
Try:
comm.CommandText = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (#Name, #IsVisible);";
To answer your first question: no, this is not the way to ensure uniqueness for country name. In your database, you should define your Countries table so that CountryName is the primary key (alternatively, you can declare some other column as the PK and define a unique constraint on CountryName).
The attempt to insert a duplicate value, then, will throw an exception, which you can handle appropriately (discard the existing record, overwrite it, prompt the user for a different value etc.).
Checking for uniqueness via your method is considered bad because A) it places logic that belongs in the database itself into your application's code; and B) it introduces a potential race condition, wherein some other application or thread inserts a value in between your read of the database and your write to it.
I thing i suggest to seperate the insert with your select statement..
someting like:
private void Insert()
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (#Name, #IsVisible)";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
comm.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar, 20);
comm.Parameters["#Name"].Value = Name;
comm.Parameters.Add("#IsVisible", System.Data.SqlDbType.Bit); comm.Parameters["#IsVisible"].Value = IsVisible;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
private void SelectInsert()
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = #Name";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
comm.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar, 20);
comm.Parameters["#Name"].Value = Name;
conn.Open();
if (comm.ExecuteScalar() == null)
{
Insert(); //your save method
}
}
}
Regards