i want to check weather a user is in my database (checking with the id). i am using the following code. It is working. i just want to know ,is this the right way or is there any other method for doing this better(like using COUNT(*) or any other query). I am doing my project in MVC4
public bool CheckUser(int mem_id)
{
bool flag = false;
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id FROM Mem_Basic WHERE Id="+ mem_id +"", con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
flag = true;
}
}
}
return flag;
}
if you want a single value you can use ExecuteSclar function. and Use parametrized queries to avoid sql injection.
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT 1 FROM Mem_Basic WHERE Id=#id", con))
{
cmd.Parameters.AddWithValue("#ID", yourIDValue);
con.Open();
var found=(int)cmd.ExecuteScalar(); //1 means found
}
}
Yes, your code will be simpler if you use a SELECT COUNT(*) query and assign the single value returned to an int instead of using the reader syntax.
Try this:
public bool CheckUser(int mem_id)
{
bool flag = false;
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Mem_Basic WHERE Id="+ mem_id +""", con))
{
con.Open();
int count = (int) cmd.ExecuteScalar();
if(count > 0)
{
flag = true;
}
}
}
return flag;
}
Instead of using ExecuteReader you can use ExecuteScalar. In my opinion your code will be more clean. See more on MSDN
About your sql query: you can check performance in SQL query analyzer in Managment Studio. See more Where is the Query Analyzer in SQL Server Management Studio 2008 R2? . But in 99% it is optimal.
You could also do something similar to yours but instead just check for null.
public bool CheckUser(int mem_id)
{
bool flag = false;
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id FROM Mem_Basic WHERE Id="+ mem_id +"", con))
{
con.Open();
if (cmd.ExecuteScalar() != null)
{
flag = true;
}
}
}
}
Related
The first SQL is executing but the second one doesn't seem to work.
When i change the query to the first one it works just fine but when I put it like that it doesn't seem to work for some reason.
I've just started learning MySQL i'm really struggling with this one and understanding the language.
//Classic One that checks if the hwid is there
public void checkHWID(string HWID)
{
string line;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE HWID = #HWID", con))
{
cmd.Parameters.AddWithValue("#HWID", HWID);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
line = reader[1].ToString();
Console.Write(line);
con.Close();
}
else
{
updateHWID(HWID);
}
}
}
}
}
//This one doesn't seem to update the hwid but when i change the query to the first one it works just fine
public void updateHWID(String HWID)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
connection.Close();
}
}
}
Your SQL statement in the updateHWID function isn't working primarily because it is missing the code that executes the command you created.
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
command.ExecuteNonQuery(); // ADD THIS LINE
}
connection.Close();
Then assuming your table only requires the hwid and no other columns then this could work. If your table has other columns that don't allow nulls then you may get an error for the missing column values.
I can't extract the values through a query and insert them into textboxes
Where am I going wrong?
Request.QueryString.Get("ID_Persona");
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID","");
cmd.Parameters.AddWithValue("#Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("#Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("#Email", TextBox20.Text);
cmd.Parameters.AddWithValue("#CodiceFiscale", TextBox22.Text);
con.Open();
cmd.ExecuteNonQuery();
}
You need to use ExecuteReader to read values, something like this:
var connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
//IDTextBox? = rdr["Id"].ToString(),
TextBox1.Text = rdr["Nome"].ToString(),
TextBox15.Text = rdr["Cognome"].ToString(),
TextBox20.Text= rdr["Email"].ToString(),
TextBox22.Text= rdr["CodiceFiscale"].ToString(),
}
}
}
}
You should use a ExecuteReader() instead of ExecuteNonQuery() since ExecuteNonQuery is meant for DML operations. Again, you need only the ID value to be passed then why you are passing unnecessary parameters to your query. Remove them all. An example below
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["Email"]));
}
I can see several issues:
You should use ExecuteReader() instead of ExecuteNonQuery()
You should provide just 1 parameter - #ID; I doubt if it should have an empty value.
You should wrap IDisposable into using
Code:
string query =
#"SELECT ID,
Nome,
Cognome,
Email,
CodiceFiscale
FROM Persona
WHERE ID = #id";
using (SqlConnection con = new SqlConnection(...))
{
con.Open();
using SqlCommand cmd = new SqlCommand(query, con)
{
// I doubt if you want empty Id here.
// I've assumed you want to pass ID_Persona
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
TextBox1.Text = Convert.ToString(reader["Nome"]);
TextBox15.Text = Convert.ToString(reader["Cognome"]);
TextBox20.Text = Convert.ToString(reader["Email"]);
TextBox22.Text = Convert.ToString(reader["CodiceFiscale"]);
}
}
}
}
I have the return ExecuteScalar inside using blocks. And when I run the method for the first time it takes some time(I am using localhost). When I run same method for the second time it is very quick, like the connection was open. WHy is it so quick the second time?
(...)
using (var sqlConnection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
sqlCmd.Parameters.Add("#database", System.Data.SqlDbType.NVarChar).Value = "dbName";
sqlConnection.Open();
return Convert.ToInt32(sqlCmd.ExecuteScalar()) == 1;
}
;
}
or here:
using (var sqlConnection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
sqlCmd.Parameters.Add("#Param1", System.Data.SqlDbType.NVarChar).Value = "ParamValue";
sqlConnection.Open();
sqlCmd.ExecuteScalar();
if ((int)sqlCmd.ExecuteScalar() != 1)
{
using (SqlCommand command = new SqlCommand("CREATE TABLE TableName (ID int IDENTITY(1,1) PRIMARY KEY, (structure code here...)", sqlConnection))
{
command.ExecuteNonQuery();
}
}
}
}
In any case, the second time I run the method that has these I get almost instant response.
I am using a using statement for validating a customer number.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand cmdCheck = new SqlCommand("SELECT COUNT(CUSTOMER_NO) FROM WEBSITE_CUSTOMERS WHERE UPPER(CUSTOMER_NO) = '" + strCustomer.Trim().ToUpper() + "';", connection))
{
int nExists = (int)cmdCheck.ExecuteScalar();
if (nExists > 0)
return true;
else
return false;
}
}
This is code previously advised to me on stackoverflow for checking preexisting records... it works great, but I would like to know if there's a way that I can use a parameter with it for the customer number since this variable is entered through the form, I want to protect it from injection. Where would I create the parameter for cmdCheck when its in a using statement like this?
Add the parameter after you've initialized the command. A convenient method is AddWithValue:
const string sql = #"SELECT
COUNT(CUSTOMER_NO)
FROM
WEBSITE_CUSTOMERS
WHERE
UPPER(CUSTOMER_NO) = #CUSTOMER_NO;";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmdCheck = new SqlCommand(sql, connection))
{
cmdCheck.Parameters.AddWithValue("#CUSTOMER_NO", strCustomer.Trim().ToUpper());
connection.Open();
int nExists = (int)cmdCheck.ExecuteScalar();
return nExists > 0;
}
}
In some programming contexts getting a scalar value from a sql query is easy:
RowCount = Connection.Execute("SELECT Count(*) FROM TableA").Fields(0).Value
In C#, given a SqlConnection variable conn that is already open, is there a simpler way to do this same thing without laboriously creating a SqlCommand, a DataReader, and all in all taking about 5 lines to do the job?
SqlCommand has an ExecuteScalar method that does what you want.
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
If you can use LINQ2SQL (or EntityFramework) you can simplify the actual query asking to
using (var context = new MyDbContext("connectionString"))
{
var rowCount = context.TableAs.Count();
}
If LINQ2SQL is an option that has lots of other benefits too compared to manually creating all SqlCommands, etc.
There is ExecuteScalar which saves you at least from the DataReader:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
(Example taken from this MSDN documentation article)
You do not need a DataReader. This example pulls back the scalar value:
Object result;
using (SqlConnection con = new SqlConnection(ConnectionString)) {
con.Open();
using (SqlCommand cmd = new SqlCommand(SQLStoredProcName, con)) {
result = cmd.ExecuteScalar();
}
}
Investigate Command.ExecuteScalar:
using(var connection = new SqlConnection(myConnectionString))
{
connection.Open();
using(var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = mySql;
var result = (int)command.ExecuteScalar();
}
}
If you're feeling really lazy, encapsulate it all in an extension method, like we do.
EDIT: As requested, an extension method:
public static T ExecuteScalar<T> (this SqlConnection connection, string sql)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentNullException("sql");
}
using(var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
return (T)command.ExecuteScalar();
}
}
Note, this version assumes you've properly built the SQL beforehand. I'd probably create a separate overload of this extension method that took two parameters: the stored procedure name and a List. That way, you could protect yourself against unwanted SQL injection attacks.