tags:

views:

72

answers:

3

I am trying to write the value of 3 variables (Username, Email, Password) to an SQLite Database. I can write text to the database but not a variable. How would I do this?

My Code:

SQCommand.CommandText = "INSERT INTO login_data (username, password, email) VALUES (Username, Password, Email)"
+2  A: 

The bad way: Concatenate the string with your values by using String.Format() method.

The better way: Use a Parameterized Query. Check the link: http://www.4guysfromrolla.com/webtech/092601-1.shtml

Mike C.
I'm not sure I understand. Is there no way to just write the variable names into the SQL command, sot hat their values are placed into the table?
Mark Provan
Did you read the link I provided? It will tell you exactly how to do it. And PLEASE do not use the method noted by John K below, which is the same as the bad method I noted above.
Mike C.
+1  A: 

I would take a step back and look at your application architecture a little more. In most cases it makes sense to use an Object Relational Mapper (ORM) tool when accessing a database. If you want to use SQLite (which is a great little database) for a simple domain model like the one you are describing I would suggest that you take a look at Subsonic's SimpleRepository data access system. It should make short work of your problem.

Mark Ewer
A: 

I'm not a VB guy so I'm guessing here...

SQCommand.CommandText = "INSERT INTO login_data (username, password, email) VALUES ("  + Username + "," + Password + "," + Email + ")"

There are better ways to do this, but for quick and dirty this should get the job done.

Edit:---- Because of all of the drive-bys saying this is bad practice I guess I should add a caveat here.

IFF the contents of these variables were provided by the user, AND they have not already been either Escaped or validated in some way. They might contain SQL commands, so a simple concatenation at this point could expose your database to a SQL Injection attack.

I should also tip my hat to all of the programmers who can tell from looking at only a single line of code and knowing nothing else about the program that simple concatenation is clearly the wrong thing to do here. Your understand of code is clearly magical.

John Knoeller
Yes, but this leaves the door wide open for a SQL Injection attack. This is a bad, bad practice.
Mike C.
Cut the guy some slack. He's trying to figure out how to use *variables* right now. He's not ready for best practices.
John Knoeller
Is it ever too early for best practices, especially when it comes to DATABASE SECURITY!?!?!?
Mike C.
This is an industry worst practice. You need to escape your variables to avoid SQL Injection attacks.
Mark Ewer