Inserting data into database, can't figure it out - c#

I'm trying to understand how to insert data into my database, so i looked at many tutorials, and i couldn't understand how to do it. one tutorial got me as far as this:
public partial class Register : System.Web.UI.Page{
public string ID, Pass, Email, BDYear, BDMonth, BDDay, FullName;
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack){
ID = Request.Form["ID"];
Pass = Request.Form["PW"];
Email = Request.Form["EMAIL"];
BDYear = Request.Form["BDYear"];
BDMonth = Request.Form["BDMonth"];
BDDay = Request.Form["BDDay"];
FullName = Request.Form["FullName"];
cmd = new SqlCommand("INSERT INTO UserInfo (ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) VALUES (ID, Pass, Email,BDYear, BDMonth, BDDay, FullName)");
}
}
}
But it doesn't actually work, or shows a sign of it working, and i think i need help of someone telling me exactly what to do in my situation.
I don't know if any of what is written here is correct, but please i need guidance.
All the variables are set in the aspx page according to those names.

You should try something like this:
set up your query statement as a string
put your SqlCònnection and SqlCommand into using(..) { ... } blocks to ensure proper disposal
define parameters with explicit types, set their values
open the connection, execute query, close connection
This would be the code to use:
-- your INSERT statement:
string query = "INSERT INTO UserInfo(ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) " +
"VALUES (#ID, #Pass, #Email, #BDYear, #BDMonth, #BDDay, #FullName);";
-- define your connection to the database
using (SqlConnection conn = new SqlConnection("server=.;database=test;Integrated Securiy=SSPI;"))
-- define your SqlCommand
using (SqlCommand cmd = new SqlCommand(query, conn))
{
-- define the parameters and set their values
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;
cmd.Parameters.Add("#Pass", SqlDbType.VarChar, 50).Value = Pass;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 255).Value = Email;
cmd.Parameters.Add("#BDYear", SqlDbType.Int).Value = BDYear;
cmd.Parameters.Add("#BDMonth", SqlDbType.Int).Value = BDMonth;
cmd.Parameters.Add("#BDDay", SqlDbType.Int).Value = BDDay;
cmd.Parameters.Add("#Fullname", SqlDbType.VarChar, 200).Value = Fullname;
-- open connection, execute query, close connection
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
Of course, with the parameters, I could only guess what datatypes they would be - you might need to adjust that! Also: the connection string in the constructor of the SqlConnection object of course needs to be adapted to your needs - again, I was just guessing what it might be like - adapt as needed!

You have not connected to the database and also you haven't executed the command.
Here is an example from MSDN:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection%28v=vs.110%29.aspx
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
You should provide connection string which depends on your DB type and location.

You need to define a sqlconnection first else how will the .net framework know which database to use, where its located etc.
sqlconnection con;
sqlcommand cmd;
con = new sqlconection("your connection string goes here");
cmd = new sql command("your query", con); //we are telling cmd that you need to
// fire the query using con which is a connection object which ultimately
// contains database connection information
con.open();
cmd.ExecuteNonQuery();
con.close();
I don't think data adapter is required here for inserting data. Data adapter is generally used when performing "select" queries. Data adapter generally fills the dataset.
More info about creating a connection string can be found on the below links:-
How to create a connection string in asp.net c#

cmd = new SqlCommand("INSERT INTO UserInfo (ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) VALUES ("+ID+", "+Pass+", "+Email+","+BDYear+", "+BDMonth+", "+BDDay+", "+FullName+")");
this may work but i suggest use SqlCommand with parameter.
this articles can help you .
http://msdn.microsoft.com/tr-tr/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

Related

'ExecuteReader: Connection property has not been initialized.' [duplicate]

This question already has answers here:
ExecuteReader: Connection property has not been initialized
(7 answers)
Closed 1 year ago.
I am new to C# and I have been trying to create a login using ADO.NET and WinForm but when I try logging in I get this error;
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'
I don't seem to know what is wrong.
private void bteAdminLog_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-RCPAL7F;Initial Catalog=iCubeDB;Integrated Security=True";
con.Open();
String txtUser = txtUsername.Text;
String txtPass = txtPassword.Text;
string query = "SELECT * FROM AdminLogin WHERE Username =#user AND Password = #Pass";
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(new SqlParameter("#user", txtUser));
cmd.Parameters.Add(new SqlParameter(" #Pass", txtPass));
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows == true)
{
MessageBox.Show("Done");
}
else
{
MessageBox.Show("not done");
}
}
Your SqlCommand didn't pass in with the query and conn
You should do it as:
SqlCommand cmd = new SqlCommand(query, con);
And for the Parameters part, you set the parameter with a respective datatype includes length/size (match with your database column) and then assign the value for each parameter:
cmd.Parameters.Add("#user", SqlDbType.Varchar, 10).Value = txtUser;
cmd.Parameters.Add("#Pass", SqlDbType.NVarchar, 50).Value = /* hashed txtPass */;
The third parameter in cmd.Parameters.Add() is for datatype's size/length.
UPDATED:
[1st edit version]
As confirmed with Post Owner that the passwords stored are hashed in the database. Thus I remove the previous remark.
[2nd edit version]
Thanks for #Charlie 's concern, so I edit the answer to include the data type's length/size.
References:
SqlCommand
Reason not to apply AddWithValue()

How to insert data into a database table using a SqlCommand

I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.

C# simple code to write an INSERT query is giving an exception

I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}

How do I check if a user name already exists in Database

I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?
"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects

Insert data into SQL Server from C# code

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query

Categories