Programmatically writing to a database - c#

I have an ASP.Net website which is connected to an SQL Server. In a previous project (VB) I used the following code to write to my database:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
Dim insertSql As String = "INSERT INTO tblProfile(UserID, UserName, Title, FirstName, LastName, MiddleName, DateofBirth, Gender, HomePhoneNumber, MobilePhoneNumber, Address, StreetName, StreetType, Suburb, PostCode, State, Country) VALUES(#UserID, #UserName, #Title, #FirstName, #LastName, #MiddleName, #DateofBirth, #Gender, #HomePhoneNumber, #MobilePhoneNumber, #Address, #StreetName, #StreetType, #Suburb, #PostCode, #State, #Country)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#UserID", newUserGuid)
myCommand.Parameters.AddWithValue("#UserName", newUserName)
myCommand.Parameters.AddWithValue("#Title", Title.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#FirstName", FirstName.Text)
myCommand.Parameters.AddWithValue("#LastName", LastName.Text)
If MiddleNames.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MiddleName", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MiddleName", MiddleNames.Text)
End If
DateofBirth.Text = YearofBirth.Text + "-" + MonthofBirth.Text + "-" + DayofBirth.Text
myCommand.Parameters.AddWithValue("#DateofBirth", DateofBirth.Text)
myCommand.Parameters.AddWithValue("#Gender", Gender.SelectedItem.Text)
If HomePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#HomePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#HomePhoneNumber", HomePhoneNumber.Text)
End If
If MobilePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", MobilePhoneNumber.Text)
End If
myCommand.Parameters.AddWithValue("#Address", AddressNumber.Text)
myCommand.Parameters.AddWithValue("#StreetName", StreetName.Text)
myCommand.Parameters.AddWithValue("#StreetType", StreetType.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Suburb", Suburb.Text)
myCommand.Parameters.AddWithValue("#PostCode", Postcode.Text)
myCommand.Parameters.AddWithValue("#State", State.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Country", Country.SelectedItem.Text)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
I've now changed to C#, and am having problems altering this code. So far I have:
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
String insertSql = "INSERT INTO tbl_UserProfiles VALUES(#UserID, #FirstName, #LastName, #YearOfBirth, #Country)";
SqlCommand myCommand = new SqlCommand(insertSql, connectionString);
myCommand.Parameters.AddWithValue("#UserID", newUserGuid);
myCommand.Parameters.AddWithValue("#FirstName", FirstNameTB.Text);
myCommand.Parameters.AddWithValue("#LastName", LastNameTB.Text);
myCommand.Parameters.AddWithValue("#YearOfBirth", YearDDL.SelectedItem.Text);
myCommand.Parameters.AddWithValue("#Country", CountryDDL.SelectedItem.Text);
try
{
connectionString.Open();
myCommand.ExecuteNonQuery();
}
finally
{
connectionString.Close();
}
Which I've tried to create after looking at a few tutorial sites and my own previous code. But, I believe I'm doing something wrong here:
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
as I get the squiggly red underline.

try this....
Use SqlConnection
Using myConnection As New SqlConnection(connectionString) you did not convert this line to C#
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
SqlConnection con = new Sqlconnection(connectionString);
String insertSql = "INSERT INTO tbl_UserProfiles VALUES(#UserID, #FirstName, #LastName, #YearOfBirth, #Country)";
SqlCommand myCommand = new SqlCommand(insertSql, con);
myCommand.Parameters.AddWithValue("#UserID", newUserGuid);
myCommand.Parameters.AddWithValue("#FirstName", FirstNameTB.Text);
myCommand.Parameters.AddWithValue("#LastName", LastNameTB.Text);
myCommand.Parameters.AddWithValue("#YearOfBirth", YearDDL.SelectedItem.Text);
myCommand.Parameters.AddWithValue("#Country", CountryDDL.SelectedItem.Text);
try
{
con.Open();
myCommand.ExecuteNonQuery();
}
finally
{
con.Close();
}

It looks like you are trying to Open() a connection string :)
Translate
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
To
using (var myConnection = new SqlConnection(connectionString))
using (var myCommand = new SqlCommand(insertSql, myConnection))
{
myConnection.Open();
...
myCommand.ExecuteNonQuery();
}
using in C# on your SqlConnection and SqlCommand will guarantee that Dispose() is called on both objects, irrespective of whether success or fail (and close connections, cleanup etc)

Make sure you have
using System.Configuration
at the top of the file. Also does your web.config file contain a configuration > configSections > configSections section?

Related

How do inject from Asp.net to a SQL database?

I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();

An attempt to attach an auto-named database for file …LoginDB.mdf failed

string _connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\James JJ\Desktop\jj\Web App\Website\App_Data\LoginDB.mdf;Integrated Security=True";
string _query = "INSERT INTO [RegistrationTable] (Email, Password, HomeAddress, PostalCode, Gender) VALUES (#email, #password, #haddress, #postalcode, #gender)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#email", Emailtxt.Text);
comm.Parameters.AddWithValue("#password", Passwordtxt.Text);
comm.Parameters.AddWithValue("#homeaddress", hAddresstxt.Text);
comm.Parameters.AddWithValue("#postalcode", Postaltxt.Text);
comm.Parameters.AddWithValue("#gender", gender);
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("RegistrationSuccess.aspx");
}
}
I really tried all the solutions on the net but I still keep getting errors.

Insert String value into Database C#

I've got my passwords to be hashed in my ASP.NET Webforms.
How do I then enter the hashed password into the database via a string?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName, #surname, #email, #username, #passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.ToString("passwordHash");
cmd.ExecuteNonQuery();
I knew I couldn't use .AddWithValue and thought of .ToString may have been the one to use.
I am new to C#.
Thanks.
Does this work?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
{
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName,#surname,#email,#username,#passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.AddWithValue("passwordHash", passwordHash);
cmd.ExecuteNonQuery();

C# SQL Update CommandText and Parameters

I created a simple SQL database that has one table, tblCustomerInformation, and three columns :
FirstName,
LastName,
and Email.
I'm attempting to update it however when I run the code that I listed below the program does nothing.
It doesn't crash and give me errors it just does nothing.
I'm fairly certain that my UPDATE statement is correct. I'm not sure why this isn't working at this point.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE (FirstName = #fn)";
//cmd.Parameters.Add("#ln", SqlDbType.NVarChar);
//cmd.Parameters["#ln"].Value = txtLastName.Text;
//cmd.Parameters.Add("#em", SqlDbType.NVarChar);
//cmd.Parameters["#em"].Value = txtEmail.Text;
//cmd.Parameters.Add("#fn", SqlDbType.NVarChar);
//cmd.Parameters["#fn"].Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Use this. The arrangement of cmd.Parameters... code should not be jumbled. Base it on the arrangement in your query.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE FirstName = #fn";
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Have encountered this kind of error once.

Inserting values into a SQL Server database using ado.net via C#

I have created a simple program to insert values into the table [regist], but I keep getting the error
Incorrect syntax near ')'
on cmd.ExecuteNonQuery();:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " #textBox1.Text, #textBox2.Text, #textBox3.Text, #textBox4.Text, #comboBox1.Text,#comboBox2.Text,#textBox7.Text" + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I am new to this and I am really confused.
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
is not vulnerable to SQL injection attacks
performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FN, #LN, #UN, #Pass, #Age, #Gender, #Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("#FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("#LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("#UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("#Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("#Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}

Categories

Resources