Inserting into MySQL database from C# Webforms, give ArgumentException - c#

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

Related

Unable to open database connection from configuration value

Firstly I am aware that this has been asked many times, but I could not find anything related to my problem specifically. basically I have text inputs I need to insert into a local DB, I've checked my connection string many times, and pretty certain it isn't the problem.
<add name="ElectricsOnline"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\electricsonline.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
and here is the method for inserting
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (var connection = new SqlConnection("ElectricsOnline"))
{
connection.Open();
var sqlStatement = "INSERT INTO Orders (FirstName, LastName, Phone, Address, Suburb, State, Postcode, Ctype, CardNo, ExpDate, Email) VALUES(#FirstName, #LastName, #Phone, #Address, #Suburb, #State, #Postcode, #Ctype, #CardNo, #ExpDate, #Email)";
using (var cmd = new SqlCommand(sqlStatement, connection))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstname.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastname.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Suburb", txtSuburb.Text);
cmd.Parameters.AddWithValue("#State", txtState.Text);
cmd.Parameters.AddWithValue("#Postcode", txtPostcode.Text);
cmd.Parameters.AddWithValue("#Ctype", ddlCtype.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#CardNo", txtCardno.Text);
cmd.Parameters.AddWithValue("#ExpDate", txtExpDate.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.ExecuteNonQuery();
}
}
Response.Redirect("CheckoutReview.aspx");
}
Source error shows this
Format of the initialization string does not conform to specification starting at index 0.
Line 22: {
Line 23:
Line 24: using (var connection = new SqlConnection("ElectricsOnline"))
Line 25: {
Line 26: connection.Open();
Any help would be greatly appreciated!
You cannot use the name of your connection from configuration file directly, because new SqlConnection(...) needs a connection string itself, not its name from the config file.
You need to retrieve connection string from config before using it to create connections. Change your code as follows:
var connStr = System
.Configuration
.ConfigurationManager
.ConnectionStrings["ElectricsOnline"]
.ConnectionString;
using (var connection = new SqlConnection(connStr)) {
...
}
new SqlConnection("ElectricsOnline")
I don't know where you got the idea that you could pass in the name of a configuration value. You need to pass in the connection string. Read it from your configuration and pass it to the constructor.

Can't write data into MS Access database with C# [duplicate]

This question already has an answer here:
Syntax error in INSERT statement into MS Access
(1 answer)
Closed 7 years ago.
I have already build a successful login form. But I want to have the opportunity to create a new account. I have two textboxes; one for username and one for password. Once the button is clicked, it needs to write this data to a MS Access 2002-2003 database file. But when I click the button I get the following error message:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
This is the code I am using:
private void buttonRegistreren_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Gebruikers (Username, Password) values('" + textBoxUserregist.Text + "', '" + textBoxPassregist.Text + "')";
command.ExecuteNonQuery();
connection.Close();
}
Somebody knows what I am doing wrong?
Password is a reserved keyword in MS-Access, you need to encapsulate it between square brackets
command.CommandText = "INSERT INTO Gebruikers (Username, [Password]) ...."
said that please remember that string concatenations to build sql command is a very bad practice and leads to numerous problems. Start using parameters as soon as possible as in the example below
private void buttonRegistreren_Click(object sender, EventArgs e)
{
using(OleDbConnection cn = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand(#"INSERT INTO Gebruikers
(Username, [Password]) values(#name, #pwd)", cn))
{
cn.Open();
command.Parameters.Add("#name", OleDbType.NVarWChar).Value =textBoxUserregist.Text ;
command.Parameters.Add("#pwd", OleDbType.NVarWChar).Value = textBoxPassregist.Text;
command.ExecuteNonQuery();
}
}

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

visual studio C# connect textbox to database

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.

C# log in app with SQL [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Hi I'm trying to get data from a local sql service database to take the input from a user register form. but when i push the button its not recorded onto the serviceable database.
do i need to use execute non query? how would i fix this code up? thanks
using System.Data.Sql;
using System.Data.SqlClient;
namespace Paddle_Power
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
MessageBox.Show("open");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
string username = textBox1.Text;
string password = textBox2.Text;
string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'");
sqlquery = "INSERT INTO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
command.Parameters.Clear();
}
}
}
Something along the lines of the following should hopefully do it. There's some room for improvement, but I at least hope it solves the problem you're having.
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
object queryResult = null;
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open(); // Open connection
// SELECT
using (SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE Username = #Username AND Password = #Password", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
queryResult = cmd.ExecuteScalar();
}
// INSERT
using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] (Username, Password) VALUES (#Username, #Password)", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
}
}
You can requse the first SqlCommand object or create a new one. There's very little difference with either way you choose to do it.
queryResult is just there for storing the result of cmd.ExecuteScalar(). You can map it to an object if you want (when selecting multiple columns) or cast it to a new type (if you're selecting a single column).
The direct answer is yes, you need to execute a non query. You see, you've prepared the command but you have not issued it. jstnasn's example should be very helpful. Take note of the using statements -- these will implicitly close the command when you exit the using statement, thus ensuring that the command is always closed when done.
The same occurs for the SqlConnection -- the using helps make sure that the connection is disposed of properly. However, if your database connection string allows connection pooling, then I believe the using statement will merely kill your object, without actually killing the connection to the database. This is advantageous because you will have lower I/O overhead the next time you need to open a database connection -- you'll just be connecting to an existing TCP/IP socket rather than opening a new on.
You have no parameters, nor do you ever actually send the query to the database
// parameter placeholders defined with #parameter_name
sqlquery = "INSERT INTO [User] (Username, Password) VALUES (#username, #Password);
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// This will make the query happen on the database.
// It will handle sending the parameters and all that good stuff
// http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
command.ExecuteNonQuery();

Categories