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

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()

Related

creating T-SQL form with Visual Studio

I am super newbie with Visual Studio. I want to create an application form in Visual Studio to insert data into my T-SQL database.
I have created a very simple Windows Application Form. It takes data from fields and insert them into my database. it simple and it works.
Now, what i want to do is to add the function for the app to look if values already exists in the database, so it wont create duplicates.
What im looking for to be checked is first_name, last_name and dob.
as im super newbie, i added an if statement to the Submit button (on click) like below:
private void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (txtFirstName == sqlCmd.CommandText("EXISTS first_name FROM employee"))
MessageBox.Show("already exists");
}
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#first_name", txtFirstName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#last_name", txtLastName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#dept_id", txtDepartmentID.Text.Trim());
sqlCmd.Parameters.AddWithValue("#job_title", txtJobTitle.Text.Trim());
sqlCmd.Parameters.AddWithValue("#dob", dateDOB.Text);
sqlCmd.Parameters.AddWithValue("#start_date", dateStartDate.Text);
sqlCmd.Parameters.AddWithValue("#contract_type", txtContractType.Text.Trim());
sqlCmd.Parameters.AddWithValue("#status_code", txtStatusCode.Text.Trim());
sqlCmd.Parameters.AddWithValue("#effect_date", dateEffectDate.Text);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Insertion Successful");
Clear();
}
}
void Clear()
{
txtFirstName.Text = txtLastName.Text = txtJobTitle.Text = txtDepartmentID.Text = txtContractType.Text = txtStatusCode.Text = "";
dateDOB.Text = dateEffectDate.Text = dateStartDate.Text = "";
}
obviously I'm very new and it does not work.
How can i go ahead and do this?
A few things to mention on this portion:
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (txtFirstName == sqlCmd.CommandText("EXISTS first_name FROM employee"))
MessageBox.Show("already exists");
}
A SqlCommand object can have several command types, 2 of which are CommandType.StoredProcedure (which you used to insert your new records) and CommandType.Text which is used to supply plain SQL directly. For this case you want to set it as plain text so change that line to:
sqlCmd.CommandType = CommandType.Text;
The first parameter of the constructor of the SqlCommand is the command text. If the command is gonna be a stored procedure call, then you need to pass the SP name (which you've done when inserting your new row), but if you want plain SQL then you can write it here (I modified the SQL to actually search for the first name in a safe way, preventing SQL Injection):
SqlCommand sqlCmd = new SqlCommand("SELECT first_name FROM employee WHERE first_name = #firstName", sqlCon);
DbParameter firstNameParameter = new SqlParameter("#firstName", txtFirstName.Text.Trim());
sqlCmd.Parameters.Add(firstNameParameter);
You need to execute the command with the ExecuteReader() method, and this will return a reader object you need to use to retrieve it's results (the SQL might return several rows).
using (DbDataReader reader = sqlCmd.ExecuteReader())
while (reader.Read())
{
MessageBox.Show("already exists");
break;
}
This is a head-start so you can keep on coding, many things to improve yet but might be too much if explained all of a sudden.
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT first_name FROM employee WHERE first_name = #firstName", sqlCon);
DbParameter firstNameParameter = new SqlParameter("#firstName", txtFirstName.Text.Trim());
sqlCmd.Parameters.Add(firstNameParameter);
sqlCmd.CommandType = CommandType.Text;
sqlCon.Open();
using (DbDataReader reader = sqlCmd.ExecuteReader())
while (reader.Read())
{
MessageBox.Show("already exists");
break;
}
}

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.

Inserting data into database, can't figure it out

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

What is the proper syntax code in using datetimepicker in visual studio c#?

Can anyone tell me what is the proper syntax code in using datetimepicker that would be saved directly to my Microsoft sql 2005? I'm using visual studio 2008 c#.
Here is my code:
private void button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
SqlDataAdapter dad = new SqlDataAdapter();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
dateTimePicker1.Format = DateTimePickerFormat.Short;
string dateStr = Convert.ToString(dateTimePicker1.Text);
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro", conn);
dad.InsertCommand.Parameters.Add("#School_Name", SqlDbType.VarChar).Value = textBox1.Text;
dad.InsertCommand.Parameters.Add("#Province", SqlDbType.VarChar).Value = comboBox1.Text;
dad.InsertCommand.Parameters.Add("#City", SqlDbType.VarChar).Value = textBox2.Text;
dad.InsertCommand.Parameters.Add("#Brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.InsertCommand.Parameters.Add("#Lot_Num", SqlDbType.VarChar).Value = textBox5.Text;
dad.InsertCommand.Parameters.Add("#Area", SqlDbType.Int).Value = textBox6.Text;
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.InsertCommand.Parameters.Add("#Cenro", SqlDbType.VarChar).Value = textBox8.Text;
conn.Open();
dad.InsertCommand.ExecuteNonQuery();
conn.Close();
}
The problem here is the datetimepicker, in my sql server Mem_Date_Rec is a datetime, so whenever I try to run it and save something on my database,
dad.InsertCommand.ExecuteNonQuery();
Keeps on saying "Incorrect syntax near '#Cenro'."
Can anyone help me out here please, it would be a really great help.
I feel like you try to insert your parameter to dad.InsertCommand command not cmd command.
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
Because your dad.InsertCommand has a parameter called #Mem_Date_Rec, not cmd. I have no idea what is your cmd for exactly. It's useless this case. You can't add a parameter value in an SqlCommand that doesn't have any parameter definition.
Also use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection conn = new SqlConnection(ConnectionString))
using(SqlCommand cmd = conn.CreateCommand())
{
//
}
If you want to write a proper syntax code, you need start reading a book, articles, blogs, examples etc..
edit
You're missing something in your SQL. Change this:
> dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools
> (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec,
> Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area,
> #Mem_Date_Rec, #Cenro", conn);
To this
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro)", conn);
INSERT INTO table (columns) values (value)
you had: INSERT INTO table (columns) values (value

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

Categories