Inserting data into SQL table from asp.net form - c#

I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:
public static SqlConnection GetConnection()
{
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
}
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = GetConnection();
try
{
myConnection.Open();
String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
+fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
+ dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";
SqlCommand myCommand = new SqlCommand(myQuery, GetConnection());
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
myConnection.Close();
}
}
The error occurs in my GetConnection() method where I return the connection. The error I get is:
An exception of type 'System.ArgumentException' occurred in
System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0.
I do not know how to get past this problem but any help is very appreciated.

Your problem lies in
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.
Standard Connection with username and password:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
Trusted Connection:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
You might want to look at this question for example:
How to set SQL Server connection string?

Pijemcolu's answer is correct, but I think several things can be added to enhance your code:
1) use proper names for variables. E.g.: connection string is different from actual connection
public static SqlConnection GetConnection()
{
// if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
return new SqlConnection(connStr);
}
2) Try to dispose disposable objects (i.e. implement IDisposable) should be properly disposed.
Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here).
The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = null;
try
{
using (myConnection = GetConnection())
{
myConnection.Open();
String myQuery = #"
INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password])
values (#firstName, #lastName, #eMail, #dob, #userName, #password)";
using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
{
myCommand.Parameters.AddWithValue("#firstName", fNameBox.Text);
myCommand.Parameters.AddWithValue("#lastName", lNameBox.Text);
myCommand.Parameters.AddWithValue("#eMail", emailBox.Text);
myCommand.Parameters.AddWithValue("#dob", dobBox.Text);
myCommand.Parameters.AddWithValue("#userName", userNameBox.Text);
myCommand.Parameters.AddWithValue("#password", passwordBox.Text);
myCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (myConnection != null)
myConnection.Close();
}
}
3) Password storage
It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here.

Related

Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows

I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}

ASP.net newline is constante

i have been trying to insert data to my database with ASP.net
the code with which i have been trying to insert data:
protected void btnInsert_Click(object sender, EventArgs e)
{
// connection
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"Data Source=YANNICK\SQLEXPRESS; Initial Catalog=Klas; Integrated Security=True";
SqlCommand command = new SqlCommand();
command.Connection = connection;
// values de insert statement toewijzen
command.Parameters.AddWithValue("#kijkerv", txtGastV.Text);
command.Parameters.AddWithValue("#kijkerT_V", txtGastT_V.Text);
command.Parameters.AddWithValue("#KijkerA", txtGastA.Text);
command.Parameters.AddWithValue("#KijkerEmail", txtEmail.Text);
command.Parameters.AddWithValue("#Kijkershow", txtShowId.integer;
// insert statement
command.CommandText = "INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);";
try {
connection.open();
int rowsAffected = command.ExecuteNonQuery();
} catch (Exception ex) {
// handle exception
} finally {
connection.close();
}
}
the error message is: newline in constant
what does this error mean/ how to fix it?
Your query string CommandText is in two lines. Remove the newline or put # before your query string like this :
command.CommandText = #"INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);"
i have found my own problem:
i had forgotten to add the libraries to set up a connction to my sql into my file
the code would look like this:
// library to work in DATABASES
using System.Data;
// library especially for SQL
using System.Data.SqlClient;

How to create exception for database file not found in c#

I have to connect my code to the access database but mainly, have to provide clear exception if that database file is not located in given location (like file not found). For this code :
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
I want to display message if test database is not present there. What can I do ? please suggest. thank you
I think you can use the static method File.Exists:
if(!File.Exists("Z:\\test.accdb"))
throw new FileNotFoundException();
try
{
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
//print the message you want;
}

C# Database issue

Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(#userName, #passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)
You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (#userName, #passWord)";
And add:
command.Connection = connection;
to associate your Command object with the connection object.
Your code should look something like this:
Set the connection object.
Specify the table name as #LarsTech has mentioned.
It is a best practice to use two part notation when specifying table names like [Schema name].[Table Name]. So, you have to specify your table name like dbo.MyTable
Code snippet:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO dbo.MyTable (userName, password) VALUES (#userName, #passWord)";
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
finally
{
connection.Close();
}
}
The form runs fine and doesn't return any errors.
That's probably because you're swallowing them. Get rid of (or log) your catch (Exception ex).
In general, the .NET BCL is well-designed - if a method isn't going to work, you will get an exception.
[Now] I have the error 'ExecuteNonQuery: Connection property has not been initialized.'
Right. You need to pass the SqlConnection to the SqlCommand:
SqlCommand command = new SqlCommand();
command.Connection = connection;

SqlCommand Method Error while executing INSERT query in WPF Application

I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?
conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";

Categories