SQL not executing - c#

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.

Related

Check a field is in sql database using c#

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;
}
}
}
}

Cannot insert data into mbf database

I have been trying to insert data into a sql database for the last hours. for one or other reason I am able to connect to the database, but no data is inserted into the database. if I run the sql statement directly in the database it does seem to work. So therefore, I was able to conclude that the statement is correct. Furthermore, there were no errors in runtime. I have got the following c# code:
//Neither of these statements seem to work.
string sqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
string altSqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (#a,#b,#c,#d,#e,#f,#g,#h,#i)";
foreach (DataRow row in importData.Rows)
{
using (SqlConnection conn = new SqlConnection(form1.Properties.Settings.Default.showConnectionString))
{
using (SqlCommand insertCommand = new SqlCommand())
{
insertCommand.Connection = conn;
insertCommand.CommandText = sqlStatement;
insertCommand.CommandType = CommandType.Text;
insertCommand.Parameters.AddWithValue("#a", row["CUE"].ToString());
insertCommand.Parameters.AddWithValue("#b", row["HH"].ToString());
insertCommand.Parameters.AddWithValue("#c", row["MM"].ToString());
insertCommand.Parameters.AddWithValue("#d", row["SS"].ToString());
insertCommand.Parameters.AddWithValue("#e", row["FF"].ToString());
insertCommand.Parameters.AddWithValue("#f", row["ADDR"].ToString());
insertCommand.Parameters.AddWithValue("#g", row["Event Description"].ToString());
insertCommand.Parameters.AddWithValue("#h", row["CAL"].ToString());
insertCommand.Parameters.AddWithValue("#i", row["PFT"].ToString());
try
{
conn.Open();
int _affected = insertCommand.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
}
}
}
}
if I change the connection parameters to something false, an error occurs, so that seems correct.
Any help would be greatly appreciated.
Thanks!
Alex
Try using this function as a template, big difference is that it is opening the connection before creating the command. I've not seen it done the way you have it setup. You also really should be opening the connection outside of the for loop, not in the for loop. Why open and close it repeatedly; the foreach should be inside the inner 'using'
public void ExecuteQuery(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
cmd.ExecuteNonQuery();
}
}
}

Issue with calling two methods in data access method

I have this method:
public bool ActivateUser(string username, string key)
{
var user = this.GetUser(username, true);
if (user != null)
{
if (user.NewEmailKey == key)
{
string query = "usp_ActivateUser";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#p_Username", username);
cmd.Parameters.AddWithValue("#p_LastModifiedDate", DateTime.Now);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
}
}
}
else
return false;
}
else
return false;
}
As you can see I call GetUser() method first to get user and later use data for another database call. But something goes wrong.
There is already an open DataReader associated with this Command which must be closed first.
Here is the get user method:
public User GetUser(string username, bool nonMembershipUser)
{
string query = "usp_GetUser";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#p_Username", username);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{...
Your problem is here.
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
You are calling cmd.ExecuteNonQuery() but the command is already being used by the reader inside this using block.
Since your code doesn't really do anything meaningful with the reader why not remove the block entirely and call cmd.ExecuteNonQuery() ?
Why do you do cmd.ExecuteReader() in the using statement, then cmd.ExecuteNonQuery(); on the very next line?
Why use the ExecuteReader() at all as you are simply returning from the database call without checking the result - ExecuteNonQuery will suffice for this.
this is the problem, in ActivateUser:
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
You can't open a Reader on an SqlCommand object and then execute another query on that command objct without first closing the Reader - which won't happen until that last "}".
Actually I'm not sure you even need the Reader in this case - did you maybe copy/paste from your GetUser function? All you should need is
cmd.ExecuteNonQuery();
return true;
Also, I would consider wrapping code to execute readers,queries, etc, into some functions so you can re-use them. Here's what I normally use as a wrapper for readers:
public static DataTable ExecuteReader (string query,CommandType commType, params SqlParameter[] Paramerters)
{
try
{
using (SqlConnection conn = new SqlConnection("your connection string here")
{
conn.Open();
using (SqlCommand comm = new SqlCommand(conn,query))
{
conn.CommandType=commType;
if (Parameters!=null) comm.Parameters.AddRange(Parameters);
DataTable dt = new DataTable();
using (SqlDataReader reader = comm.ExecuteReader())
{
dt.Load(reader);
}
return dt;
}//end using command
}//end using connection
}
catch(Exception)
{
throw;
}
}//end function
and you can write simple wrappers for nonquery, nonreader, etc, as well.

Multiple SQL queries asp.net c#

I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?
Thanks,
EDIT: Will this work?
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query3, conn))
{
cmd.ExecuteNonQuery();
}
}
Using the MDSN Documentation as a base:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql1 = "SELECT ID,FirstName,LastName FROM VP_PERSON";
string sql2 = "SELECT Address,City,State,Code FROM VP_ADDRESS";
using (SqlCommand command = new SqlCommand(sql1,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
using (SqlCommand command = new SqlCommand(sql2,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
// If you don't using using on your SqlCommands you need to dispose of them
// by calling command.Dispose(); on the command after you're done.
} // the SqlConnection will be disposed
It doesn't matter which way you go.
SqlConnections are pooled by the operating system. You could literally open and close a connection thousands of times in a row and not incur any performance or other penalty.
How it works is:
Application makes a request to create a db connection (var c = new SqlConnection(...))
The Operating Systems connection pool looks to see if it has a connection sitting idle. If it does, you get a reference to that. If not then it spins up a new one.
Application indicates it is finished with the connection (c.Dispose())
Operating System keeps the connection open for a certain amount of time in case your app, or another one, tries to create another connection to that same resource.
If that connection stays idle until a timeout period passes then the OS finally closes and releases.
This is why the first time you make a connection to a database it might take a second to start before the command(s) can be processed. However if you close it and reopen it then the connection is available immediately. More information is here: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx
Now, as to your code, generally speaking you open 1 SqlConnection each time you make a SqlCommand call; however, it is perfectly acceptable/reasonable to make multiple SqlCommand calls while within the same block under the SqlConnection using clause.
Just bear in mind that you do NOT want to keep a SqlConnection object hanging around in your code for any longer than is absolutely necessary. This can lead to a lot of potential issues, especially if you are doing web development. Which means it's far better for your code to open and close 100 SqlConnection objects in rapid succession than it is to hold onto that object and pass it around through various methods.
Having one SqlConnection and many SqlCommands will work fine, however you must make sure that you dispose of any SqlDataReaders that are returned from previous commands before attempting to run additional commands.
using (SqlConnection conn = new SqlConnection())
{
conn.Open()
using (SqlCommand cmd = new SqlCommand("SELECT myrow FROM mytable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle first resultset here
}
}
using (SqlCommand cmd = new SqlCommand("SELECT otherrow FROM othertable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle second resultset here
}
}
}
Alternaitvely you might be able to combine your commands up into one batch and instead process multiple resultsets, like this:
using (SqlConnection conn = new SqlConnection())
{
conn.Open()
using (SqlCommand cmd = new SqlCommand("SELECT myrow FROM mytable; SELECT otherrow FROM othertable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle first resultset here, and then when done call
if (reader.NextResult())
{
// Handle second resultset here
}
}
}
}
When you are processing many resultsets you will find that batching together queries like this can significantly improve performance, however it comes at the price of added complexity in your calling code.
Open only one SQLConnection
Use the keyworkd Using as it will automatically dispose the connection.
If you open connection for each one , it can have performance problems.
Example:
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code shows how you can use an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
One more example:
public DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("your connection here")
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "your stored procedure here";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}
Purely as an alternative to the using statements:
SqlConnection con = new SqlConnection(myConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = #"SELECT [stuff] FROM [tableOfStuff]";
con.Open();
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader();
while(dr.Read())
{
// Populate your business objects/data tables/whatever
}
}
catch(SomeTypeOfException ex){ /* handle exception */ }
// Manually call Dispose()...
if(con != null) con.Dispose();
if(cmd != null) cmd.Dispose();
if(dr != null) dr.Dispose();
The major difference between this and the using statements, is this will allow you to handle exceptions more cleanly.

Simple SQL select in C#?

On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
Is there an easier way to make a simple select query? In php, I can just use mysql_query and then mysql_result and I'm done.
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
Thanks for any tips.
You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You are probably looking for SqlCommand and SqlDataReader
Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
string query = "SELECT UserId, UserName FROM Users";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
users.Add(reader.GetInt32(0), reader.GetString(1));
}
connection.Close();
}
Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.
.NET Framework Class Library
SqlCommand..::.ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
You can do something very similar:
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
conn.Open();
return cmd.ExecuteScalar();
}
you can use SqlCommands executeScalar function. Please look at the following link
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Categories

Resources