No data is inserted into my table - c#

I have a simpe table:
Users
UserID Guid doesnt allow null
Avatar image allows null
Reputation int allows null
I used the following statement:
string insertCommand = "INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
UsersIdentityToinsert(this value is a Guid, I checked its value, it isn't null).
There were no exceptions thrown. As soon as the user presses the login button, he is transfered to another page, and his record is inserted.
I followed with the debugging that that statement is executed.
When I return to my server explorer in Visual Studio 2010 and click refresh the Users table is empty. Why is that?
Connection string
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True"/>
i retrieve it from config into the code:
WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
Added:
public static void InsertUsers(Guid UsersIDentity)
{
SqlConnection sqlConnect = getSqlConnection();
SqlCommand sqlCommand = new SqlCommand(RegisterAdo.insertCommand(UsersIDentity), sqlConnect);//insert command method returns the insert statement described above
try
{
sqlConnect.Open();
sqlCommand.ExecuteNonQuery();
}
catch (Exception x)
{
HttpContext.Current.Response.Redirect("~/ErrorPage.aspx?Error=" + WRITE_ERROR);
}
finally
{
sqlConnect.Close();
}
}

Instead of using
"INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
use this:
"INSERT INTO Users (UserID) VALUES" +""+ "(CONVERT(uniqueidentifier, '"+UsersIdentityToinsert+"'))";
And you really should use a prepared Statement instead of concatenating the sql.
What about the DB-connection? Did you run any successfull statements so far? Try a simple select.

try this :
"INSERT INTO Users (UserID) VALUES ('"+UsersIdentityToinsert+"')";

There are a number of things to check
Are you connected to the right database?
Is the code that executes this SQL Statement actually working. You don't show that code. I'd be expecting a ExecuteNonQuery() on a SqlCommand object somewhere.
Do you actually open a connection to a database? Or is the connection string just in the config without being used anywhere in your code?
Also, your code is susceptible to a SQL Injection attack. You should use a parameterised query to prevent that. This article on SQL Injection Attacks will help you with how to write that.
You also have missing code which I'd expect to see. Something along the lines of this:
string insertCommand = "INSERT INTO Users (UserID) VALUES"
+""+ "('"+UsersIdentityToinsert+"')";
string cs = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(insertCommand, conn);
conn.Open();
cmd.ExexuteNonQuery();
conn.Close();

Related

How to override "duplicate entry warning" when run an append query (Access db, from c# asp.net)?

I have a query in the access database that appends email addresses from one table to another. In the source table there may be many duplicated emails. In the target table the email field is unique. Before running the query, there may already in the target table emails that are in the source table.
When running the query manually, I get a message about duplicates and I have to click on Yes to run the query anyway.
But when I try to run the query from the asp.net, c#, I get an exception and nothing is done.
How can I override the exception? I mean, how can I "tell" the system to assume I clicked on Yes after the warning?
Here is my code:
public static void RunQuery(string db, string command)
{
OleDbConnection conn = getConn(db); //set the value for conn
try
{
if (conn != null) conn.Close();
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = command; // query name
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception e)
{
log.Error(e);
throw;
}
finally
{
if (conn != null)
conn.Close();
}
}
Thanks
It has never been clear when/how the error msg of duplicates will trigger.
I find that this (in most cases) will run the append query, and errors are ignored.
This:
// run append query
using (OleDbConnection conn =
new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL =
new OleDbCommand("AddToHotelss", conn))
{
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.ExecuteNonQuery();
}
}
Now, the above runs this saved query in Access:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City = "Edmonton");
And I have a unique index on EmailName - and the above works.
So, give the "setting" of CommandType = StoredProcedure.
The above SHOULD work.
If it does not?
Then you have to consider introduction of the office.interop ACE data engine. (I don't think that's a good idea).
Or, if above idea does not work?
You have to modify your query to prevent duplicates in the first place..
The query then becomes this:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City="Edmonton")
AND
(tblHotels.EmailName NOT IN (SELECT EmailName from tblHotels2.EmailName));
So, as suggested, you re-write the query to never allow duplicates.
I would however give the commandText setting (StoredProcedure) as per above - since in the past I had that work for me. (the duplicates message did not trigger, or stop the append).

C# to database (textboxes)

I want to use my textboxes to send data to my database.
The problem is that he doesn't know loonberekening.tblWerknemer, I always get
incorrect syntax near 'tblWerknemer'
Here is a picture of my tables: http://gyazo.com/1a92845f51f56ef37e9ae3adf3f23a7c
string database = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into loonberekening.tblWerknemer (naam,voornaam) values ('"+txtNaam.Text+"','"+txtVoornaam.Text+"');";
SqlConnection cnnLoonberekening = new SqlConnection(database);
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
SqlDataReader check;
try{
cnnLoonberekening.Open();
check = scmdLoon.ExecuteReader();
MessageBox.Show("Opgeslagen");
while (check.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Try "insert into loonberekening.dbo.tblWerknemer"
also as an aside look into parameterisation of the values.
Either add ;InitialCatalog=loonberekening to the end of the connection string to specify the database or add a schema name to the query: loonberekening.dbo.tblWerknemer.
There will be nothing to read back from an insert as you appear to be attempting
You need to use an SQLCommand to prevent what will happen if you run your code with a ' anywhere in the textbox. (SQL Injection)
Try "insert into loonberekening.dbo.tblWerknemer"
or
only "insert into tblWerknemer"
then rest parts
Try rewrite the query as insert into dbo.tblWerknemer ..., because loonberekening is the database name and dbo.tblWerknemer is the actual table name
Also try to use parametrized query instead of directly passing values to prevent sql injection.
http://www.dreamincode.net/forums/topic/268104-parameterizing-your-sql-queries-the-right-way-to-query-a-database/
try this:
string database = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into tblWerknemer (naam,voornaam) values (#Naam,#Voornaam)";
using(SqlConnection cnnLoonberekening = new SqlConnection(database))
{
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
scmdLoon.Parameters.Add("#Naam",SqlDbType.VarChar).Value=txtNaam.Text;
scmdLoon.Parameters.Add("#Voornaam",SqlDbType.VarChar).Value=txtVoornam.Text;
scmdLoon.ExecuteNonQuery();
}

MySQL truncate command with parameter not working

Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?

SQL connection string for microsoft access 2010 .accdb

I am doing a simple login form using winforms and access 2010 database (.accdb) in C#.
I have the following code and it seems that the connection string is wrong. I have tried searching and found that .Jet is for access 07?? but this doesnt seem to work too.
i am an amateur at databases (code referred from msdn). I am having trouble understand which should i use for this example too.
access table name: haha
ID (PK) | password
-----------------------
1 | testing
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb");
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
comm.CommandText = "SELECT HAHA(*) FROM password";
comm.CommandType = CommandType.Text;
comm.Connection = conn;
conn.Open();
Object returnValue = comm.ExecuteScalar();
conn.Close();
MessageBox.Show((string)returnValue);
edited: the table's name is password, and the field that i want to get the value is ID.
SQL statement i wrote it as : SELECT ID FROM password
and yes, only one record in only one field in the table as the primary key.
anyway the problem is that the program hangs upon execution on the first line
-> Keyword not supported: 'provider'.
so i figured that I have a wrong connection string..
For Acces databases (.mdb, .accdb, etc...), you want to use OleDbConnection, not SqlConnection (SQL Server), like this:
conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb")
Edit: as pointed out, for access OleDbConnection should be used, not SqlConnection...
you can use a much more compact way and also be sure connection is closed and disposed in any possible case even when exceptions are thrown, by using the using statements:
your query text was also, probably wrong as others have suggested...
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb"))
using (var comm = conn.CreateCommand())
{
comm.CommandText = "SELECT password FROM HAHA";
comm.CommandType = CommandType.Text;
conn.Open();
var returnValue = comm.ExecuteScalar();
MessageBox.Show(returnValue.ToString());
}
Edit: are you sure the table HAHA only contains one row? Because the ExecuteScalar returns only one value, if you want to get 1 column but from many records you could use a DataReader or a DataSet...
comm.CommandText = "SELECT HAHA(*) FROM password";
It´s wrong.
"SELECT password FROM HAHA"
Your SQL statement should be,
SELECT * from HAHA
OR
SELECT [Password] From HAHA
EDIT:
You should change the ConnectionString.

How to save a SQL "Select" result in a variable in C#

I'm using Visual C# connected to MySQL for study purposes and I'm stuck in throwing an error to the user when he types a username that already exists.
Current code to put things into the database (it may be useless, once my question may be much more about SQL):
s = new sql(); // This calls a class that works as an adapter to connect form with the database
Conn = s.Connection;
Conn.Open();
coma = Conn.CreateCommand();
coma.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES ('"+username.Text+"','"+password.Text+"');";
coma.ExecuteNonQuery();
What I want to do it compare "username.Text" ("username" is a TextBox) with the values on database's "test" table and, if some value match, evoke a MessageBox.Show("Hey guy, this username is already in use! Try something different)
Some points about your code sample
You want to be sure that you dispose of your connection and command objects. For my answer, I've wrapped them in using statements which will take care of that for me.
You do not want to go to the database with unsanitized inputs. I am going to use parameterized queries in the example.
It's not a good idea to store passwords in plain text. I am not going to demonstrate more secure techniques, just know to look for information about encrypting passwords, salt keys, etc.
And now for some code. In this, I'm using OleDb objects, retrofit to your particular database. And, of course, provide appropriate names to tables, columns, etc.
using (OleDbConnection connection = SomeMethodReturningConnection())
using (OleDbCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OleDbParameter("#username", username));
command.CommandText = "Select Count(*) From Users where Username = #username";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OleDbParameter("#password", password));
command.CommandText = "Insert Into Users (Username, Password) Values (#username, #password)";
command.ExecuteNonQuery();
}
}
Thank you Anthony! Your answer put me on the right track. Although there is something that the people who will read this post should change from your code in order to get it working with Odbc connectors: the way as parameters are parsed and the way as the textbox content is extracted:
using (OdbcConnection connection = SomeMethodReturningConnection())
using (OdbcCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OdbcParameter("#username", username.Text));
command.CommandText = "Select Count(*) From Users where Username = ?";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OdbcParameter("#password", password.Text));
command.CommandText = "Insert Into Users (Username, Password) Values (?,?)**";
command.ExecuteNonQuery();
}
}
Thank you anyway!

Categories