Simple sql query not working - c#

I tried to insert some data into my database (sql server/local file) but it doesn't work.
public bool SaveCookie(string cookie, string expires)
{
SimpleDBM db = new SimpleDBM();
db.Connect();
try
{
string query = string.Format("INSERT INTO Cookies(cookie_value, cookie_expires) VALUES('{0}', '{1}');", cookie, expires);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
//...
SqlDataReader data = db.Query(ref cmd);
return data.Read();
}
catch
{
return false;
}
finally
{
db.Close();
}
}
The SimpleDBM class:
public class SimpleDBM {
public static string dbpath = #"...";
public static string dbname = "db.mdf";
public static string dfullPath = Path.Combine(dbpath, dbname);
public static string connStr = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True", dfullPath);
private SqlConnection con;
public void Connect()
{
con = new SqlConnection();
con.ConnectionString = connStr;
con.Open();
}
public SqlDataReader Query(ref SqlCommand cmd)
{
cmd.Connection = con;
return cmd.ExecuteReader();
}
public void Close()
{
con.Close();
}
}
Can someone point out my mistake? For other queries it seems to work fine.
Thanks in advance.

The problem seems to be that you're trying to execute a query that doesn't return a result set using the ExecuteReader method of the SqlCommand class which will attempt to execute your query and create and return a DataReader for an eventual result set.
You should use ExecuteNonQuery for INSERT and UPDATE sql statements.
SIDE NOTE
Not that it's the reason you're getting the error but you should also consider using SqlParamters instead of composing the values into the INSERT statement. Using prepared SQL statements generally gives a performance enhancement and also helps prevent SQL injection attacks.
For an example of using prepared statements, see the MSDN page or the Prepare method.

You are using a ExecuteReader when you should be using ExecuteNonQuery.
Not related to your error you really should not be using String.Format with SqlCommand. What you should do is
string query = "INSERT INTO Cookies(cookie_value, cookie_expires) VALUES(#cookie, #expires);", cookie, expires);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#cookie", cookie);
cmd.Parameters.AddWithValue("#expires", expires);
cmd.CommandText = query;
With your method ask your self if someone passed a cookie of ' ''); Drop table Cookies --? This is called a "Sql Injection Attack" and is one of the top 5 reasons websites get hacked.
EDIT
Just to help give another example of why using String.Format to pass values you did not generate is bad.

Related

MySQL insert C# fails when Connection Pooling is activated

I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?

C# - How to send Insert with #Parameters to Database Connection Class

Having a bit of an issue getting my insert to work properly. When I run the insert all within the same method, it works flawlessly... however when I try to send the Insert statement to my new Connection class (which I will have handle all database requests), I am getting the following error.
Note: I am using C# and Microsoft SQL Server.
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#CollectionGroupID".
I believe I am not sending the parameters over, however I am not sure of the best way to do this.
Here's my AddGame method:
public static void AddGame(int gameId)
{
string statement = "INSERT INTO Collection (CollectionGroupID, SharedID, UserID, GameID, Owned, Favorited, WishList, DeletedIndicator, AddUser, AddDate, ModUser, ModDate) VALUES (#CollectionGroupID, #SharedID, #UserID, #GameID, #Owned, #Favorited, #WishList, #DeletedIndicator, #AddUser, #AddDate, #ModUser, #ModDate)";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.AddWithValue("#CollectionGroupID", "0");
cmd.Parameters.AddWithValue("#SharedID", "0");
cmd.Parameters.AddWithValue("#UserID", "0");
cmd.Parameters.AddWithValue("#GameID", gameId);
cmd.Parameters.AddWithValue("#Owned", "Y");
cmd.Parameters.AddWithValue("#Favorited", "N");
cmd.Parameters.AddWithValue("#WishList", "N");
cmd.Parameters.AddWithValue("#DeletedIndicator", "N");
cmd.Parameters.AddWithValue("#AddUser", "test/admin");
cmd.Parameters.AddWithValue("#AddDate", DateTime.Now);
cmd.Parameters.AddWithValue("#ModUser", "test/admin");
cmd.Parameters.AddWithValue("#ModDate", DateTime.Now);
Connection.Open();
Connection.Statement(statement);
Connection.Close();
}
}
And here is my Statement method in my Connection class
public static void Statement(string sql)
{
Console.WriteLine("Attempting to submit data to the database...");
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e);
}
}
I feel like perhaps I am overlooking a simple solution. Any help appreciated!
-Travis W.
Command parameter is defined in SqlCommand in your AddGame method
you are passing the raw Sql over to the Statement method and inside the method you are creating another SqlCommand without parameter defined. This is why the parameters are not being passed in.
you should just do
using (SqlConnection connection = new SqlConnection(connectionString))
{
//OR using (SqlConnection connection = Connection.Open())
//If you want to keep your Connection class to avoid having to pass in connection string.
using (SqlCommand cmd = new SqlCommand(statement, connection))
{
...
cmd.ExecuteNonQuery ()
}
}
inside your AddGame method

Execute any Raw SQL Query

IS it possible to execute a raw SQL command of any type (SELECT, UPDATE, DELETE....) in C#. I am looking to add a feature similar to the SQL Server Management Studio query window where I can just type in any SQL command and it executes it. In my case I am not worried about sql injection, I know this risk with this feature. All the connection parameters are passed to me (I have a valid connection string), but I know nothing about the database itself. The SQL command is also syntactically correct before I get the command. I cannot seem to find a solution that will work in all cases, probably just overlooking the obvious solution.
Here is an ADO example for you
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"UPDATE [dbo].[USR_Users] SET [Active] = 1 WHERE Id = 1";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
You can simply use ADO .NET and show the results of the query if it executed successfully or not, just put the following code in the event handler when you want to execute your query:
using (SqlConnection conn = ConnectionClass.GetInstance().Connection())
using (SqlCommand cmd = new SqlCommand(TextBoxQuery.Text, conn))
{
conn.Open();
TextBoxNoOfRowEffected.Text = cmd.ExecuteNonQuery().ToString();
}
SqlCommand.ExecuteNonQuery() Documentation

C#: SQL can't execute the reading

I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()
Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.

SqlConnection property in a custom asp.net database component

Im making a few static classes to avoid rewriting the same code multiple times and to keep all the database related methods in the same place.
the class look like this:
public static class Database_dbSurvey
{
public static DataSet GetQuestionari()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString);
string query = "[admin].[SRV_Categorie_Lista]";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.CommandType = CommandType.StoredProcedure;
//GetDataSet use the SqlDataAdapter.fill() method
return Utils.GetDataSet(cmd);
}
etc.... (others similar methods)
}
I want to reduce the code and I want to make it more "object oriented", so I started by making a property for the SqlConnection (which is the same for every methods of this class).
private static SqlConnection connection
{
get { return new SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString); }
}
The problem is that it works perfectly with SqlDataAdapter.fill(), till I use a method like this:
using (connection)
{
connection.Open();
cmd.ExecuteNonQuery();
}
Now, the next usage of the connection will throw the "not istanziated" exception and I can't understand why.
what is the correct way to define the connection property?
p.s.
if you have other suggestion on improving the code it will be higly appreciated
EDIT:
I still dont get it why the "new" keyword do not create another istance of the SQLConnection everytime I call it.
however I made some changes to make the code safer:
private static string connection_string
{
get { return ConfigurationManager.ConnectionStrings["Connection_dbPrysmianSurvey"].ConnectionString; }
}
public static DataSet GetQuestionari(string username)
{
string query = "[dbo].[SRV_Test_Lista]";
using (SqlConnection connection = new SqlConnection(connection_string))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username);
return Utils.GetDataSet(cmd);
}
}
public static int CreaTest(string ID_questionario, string username)
{
string query = "[dbo].[srv_test_genera]";
using (SqlConnection connection = new SqlConnection(connection_string))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID_categoria", ID_questionario);
cmd.Parameters.AddWithValue("#ID_utente", username);
connection.Open();
return (int)cmd.ExecuteScalar();
}
}
But considering the fact that I have 40-50 methods it's still is a pain to rewrite the same lines 40-50 times, any suggestions?
Do not use using keyword in your case.
It will dispose the connection after that using's scope is complete by calling SqlConnection.Dispose method.
using(connection) {...}'s equivalent -
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
connection.Dispose();
}
As #Parag Meshram mentioned, using keyword disposes everything inside itself when completed.
There are two ways I can suggest:
(1) Don't make connection a static method
private SqlConnection connection() { get { return new
SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString);}
}
then use it like
SqlConnection newConnection = connection();
using (newConnection) { ... }
Or
(2) Keep your static method as is but use it like this:
try {
connection.Open();
cmd.ExecuteNonQuery(); } catch {
throw; }
This way, your connection is not disposed.
I had the same problem a year ago and that's now I resolved it, using method (2).

Categories

Resources