visual studio C# connect textbox to database - c#

I have written this simple code in c# VS 2010 to store the name and login to my local table. When i run it is shows me this massage:
"incorrect syntax near the nvarchar"
using System;
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string name =textBox1.Text;
string login =textBox2 .Text;
string sqlquery;
SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Users\\Safeen\\Documents\\Visual Studio 2010\\Projects\\WindowsFormsApplication12\\WindowsFormsApplication12\\Database1.mdf;Integrated Security=True;User Instance=True");
cn.Open();
sqlquery = "INSERT INTO Table1 (user, password) VALUES ('" + name + "','" + login + "')";
try
{
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("#user ", textBox1.Text);
command.Parameters.AddWithValue("#password ", textBox2.Text);
command.ExecuteNonQuery();
MessageBox.Show("Table1 Added");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
textBox1.Clear();
textBox2.Clear();
cn.Close();
}
}

You're providing multiple values for your parameters.
You're saying the db value of user = name and password = login, then ALSO passing in two parameters called #user and #password, without telling SQL which set is correct.
You definitely want to go with SqlCommand option and also set the SqlCommand.CommandType to the correct value. Assigning parameters like this is safe; dropping variables directly into the VALUES() clause (like you had in your original post) can open yourself to SQL Injection attacks.
I edited out a recommendation to use Stored Procs here. That's more of a personal preference I have, as per the little discussion in the comments; I like to separate out my database layer. Also, it means that if anything ever changes you just have to update your Stored Proc once instead of finding your query everywhere it could be in your app.

Related

SqlException was unhandled by codeuser

I'm building a user registration page that save user's info into a local database. However I get a SqlException error. Does anyone know what I'm doing wrong here? I'm developing the program in ASP.net and using the local database server.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Table where userName = '" + txtUN.Text + "'";
SqlCommand comm = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("user already exist");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table(UserName, name, Address, e-Mail, IC, phone, password) values(#Uname, #name, #add, #mail, #ic, #phone, #pswrd) ";
SqlCommand comm = new SqlCommand(insertQuery, conn);
comm.Parameters.AddWithValue("#Uname", txtUN.Text);
comm.Parameters.AddWithValue("#name", txtName.Text);
comm.Parameters.AddWithValue("#add", txtAdd.Text);
comm.Parameters.AddWithValue("#mail", txtEmail.Text);
comm.Parameters.AddWithValue("#ic", txtIC.Text);
comm.Parameters.AddWithValue("#phone", txtPhone.Text);
comm.Parameters.AddWithValue("#pswrd", txtPsswrd.Text);
comm.ExecuteNonQuery();
Response.Redirect("Default.aspx");
Response.Write("registration was succesful");
conn.Close();
}
catch(Exception ex)
{
Response.Write("error"+ex.ToString());
}
}
You don't give the details of the exception, (ie: exception.Message and exception.InnerException.Message) but from your code I think you have the classical "Syntax Error Near ...."
This is caused by the presence of a reserved keyword in your query text. This reserved keyword is TABLE. You could fix it enclosing the word in square brackets (or better change the name of the table to somenthing more meaningful)
string checkUser = "select count(*) from [Table] where userName = ...";
A part from this, remember to use always parameterized queries also for simple tasks as looking for logins. Last but not least, storing password in clear text inside the database is a big NO-NO from a security standpoint. Everyone, having access to your database using some kind of administrative tool, could look at the passwords of your users, someone could intercept the network traffic between user pc and database server and see the credentials sent by your application. So, please, search for password hashing on this site to find a more secure approach to this problem

LocalDB changes persist in different mdf files - Why?

I am trying to rebuild an application that originally used sqlite to now use 'localdb'. (I want an application that can create its own database locally and at runtime without requiring a pre-installed instance of sql server or sql express on the target machine)
I want to move away from using a 'third party' library (sqlite) as experience has told me it can be a pain to get it working from scratch, and towards something supposedly more straightforward to get up and running from scratch.
Using code copied (and slightly modified) from the web I have managed to create an mdf file dynamically/programmatically, but I am puzzled by what happens if I run it more than once, even if I choose a new filename each time. Namely it seems to somehow keep the changes/additions made on each run. Below is the relevant code...
public partial class Form1 : Form
{
SqlConnection conn;
public void CreateSqlDatabase(string filename)
{
string databaseName =
System.IO.Path.GetFileNameWithoutExtension(filename);
conn = new SqlConnection(
String.Format(
#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"
));
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText =
String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')"
, databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CreateSqlDatabase(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText =
"create table mytable (id int, name nvarchar(100))";
comm.ExecuteNonQuery();
comm.CommandText =
"insert into mytable (id,name) values (10,'testing')";
comm.ExecuteNonQuery();
comm.CommandText = "select * from mytable";
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
textBox1.Text +=
reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
}
conn.Close();
}
}
If I run the app once It runs through fine.
If I run the app a second time, and choose a different filename for the database it tells me 'mytable' already exists.
If I comment out the create table code it runs, but the select query returns multiple rows indicating multiple inserts (one for each time the app runs)
I am just seeking to understand why this happens. Do I need to delete database/table each time if I want the app to behave as if it has created the database/table from scratch on each subsequent run?
You have initial catalog 'master' in your connection string. Are you sure you haven't created the tables in the master database instead of the newly created database?
After the creation & detach of the database file, you could try and change your connection to:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\xxx\xxx\xxx.mdf");

Inserting into MySQL database from C# Webforms, give ArgumentException

I'm trying to create a Registration Page using Webforms that'll connect to a MySQL databse and insert the data, but it throws up an ArgumentException (even though I believe I'm following my tutorial exactly) and will not insert the data into the table.
My C# code for the Registration page is thus:
public partial class Registration : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString =
System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seniorschema.registration (Password1, Email, FirstName, LastName, Password2, Code)" +
"VALUES('" + PasswordTextBox1.Text +"','"+ EmailTextbox.Text +"','"+ firstNameTextBox.Text+"','"+ LastNameTextBox.Text + "' ,'"+ PasswordTextBox2.Text +"', '"+ CodeTextBox.Text + "' )";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
And my connection in the WebConfig file is here:
<connectionStrings>
<add name="WebAppConnString"
connectionString="server=localhost;ID=webuser;pwd=password;database=seniorschema;"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
Any Help would be most appreciated. Thanks!
I don't know what tutorial you are reading but they should never teach to use string concatenation when building an sql command text.
However, the error you get is from the connectionstring.
You should write
String connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ConnectionString;
There is also an error in the definition of the connectionstring in the web.config ( a typo?)
It is Uid=.... not ID=....
And here how I would write the code that add the record.
using MySql.Data.MySqlClient;
....
queryStr = #"INSERT INTO seniorschema.registration
(Password1, Email, FirstName, LastName, Password2, Code)
VALUES(#pwd, #email, #first, #last, #pwd2, #code";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand cmd = new MySqlCommand(queryStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#pwd",PasswordTextBox1.Text);
cmd.Parameters.AddWithValue("#email",EmailTextbox.Text );
cmd.Parameters.AddWithValue("#first",firstNameTextBox.Text);
cmd.Parameters.AddWithValue("#last",LastNameTextBox.Text );
cmd.Parameters.AddWithValue("#pwd2",PasswordTextBox2.Text );
cmd.Parameters.AddWithValue("#code",CodeTextBox.Text);
int rowAdded = cmd.ExecuteNonQuery();
}
This approach remove the string concatenation with all the complexities required to correctly code the quotes around the values, also removes any possibility of Sql Injection
Finally, but this is really an argument too broad and not immediately linked to your question.
It is a bad practice, from a security standpoint, to store passwords in clear text. If someone could get a copy of or read the registration table, he/she will be able to read the passwords of all users registered. There are proven methods that store an hash of the password to make them unreadable to onlookers

Taking data from a windows

What I need to do is basically take the users name (which is already stored as a variable) and their score (which is also a variable) and store it in my database when they press 'submit'. Here is the code I have for the button click.
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
Obviously i have changed the login details etc. I have had a look around and have only managed to find confusing codes about how to display data from a database in a form (i will do this later), but for now, i need to know how to add sName and iTotalScore into the database. (Fields are called 'Name' and 'Score' in DB)
You are going to use a combination of SqlConnection, SqlCommand and their properties. the connection is essentially the stuff of your code. The command is a literal SQL statement, or a call to a stored procedure.
A common C# idiom is to form your code around the very first line as shown here:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
The general outline is
Using a connection
instantiate and configure an SqlCommand
Use try/catch as shown.
The "using" block gives use behind the scenes cleanup/disposal of all those objects we don't need anymore when we're done; in particular the SqlConnection object.
You must learn more about these Sqlxxxxx classes, there's lots of ways to configure them to do what you want.
I am not familiar with the MySql connector, but the code should be something along the lines of:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (#name, #score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("#name",sName);
insertCommand.Paramaters.AddWithValue("#score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

Asp.net login script

i'm new to asp.net, i'm writing a login & registration script for learning database application. But the script seems not work. it stills can add duplicated username. Here is the script
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
static string temp;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from [user] where UserName='" + TextBoxUN.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
Response.Write("User Name Already Exist....<br /> Please Choose Another User Name.");
}
}
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into [user] (UserName, Password, EmailAddress, FullName, level) values (#UserName,#Password,#EmailAddress, #FullName, #level)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#UserName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Password", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#level", level.SelectedValue.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
//Response.Redirect("Login.aspx");
Label1.Text = temp;
}
catch (Exception er)
{
Response.Write("Something wrong");
}
finally
{
//Any Special Action You Want To Add
}
}
}
Any can detect the problems?
thanks
You should do the check whether the username exists inside your Button_Click, not inside Page_Load. Ideally both queries should be executed within the same SQL transaction. Also you should absolutely use parametrized query for the first one (the same way you are doing in the second query) in order to prevent SQL injection.
Set primary key on the column UserName of the table user. So you don't have to check for the user existence in the database at the time of insertion, reducing an extra call to database. This way command.ExecuteNonQuery() won't allow you to insert duplicate users and throw exception and you can take necessary actions in the catch block of your code.
Make an unique field for your user login in SQL Database.
On account creation page on account creation button click event do it as following:
try
{
SqlCommand command = new SqlCommand("INSERT INTO Users(login,password) VALUES ('" + txtLogin.Text + "','" + txtPass.Text+ "');", con);
command.ExecuteNonQuery();
Response.Redirect("login.aspx");
}
catch (SqlException)
{
lblWrongLogin.Text = "Username already exists.";
}
Basically, when you try to write a duplicate login in SQL Database you get SQL exception, so you just catch it in your application and do whatever action you need (in most cases reload registration page).
P.S.:
consider using some hashing algorithm like MD5 to hash passwords before putting them in database. Also dont forget to hash passwords client-side when logging in.
P.P.S.: use SQL parameters for login, password and every other user-entered information to prevent SQL injection.

Categories