Delete Asp.Net Databse Connection Tutorial. Receiving CS103 error code - sqldatareader

I am new to programming and found these great tutorials on the Guru99.com site. Under the insert, update, Delete Asp.Net Database Connection Tutorial I was able to make the connection to the database successfully where the message came back "Connection Made".
The problem I am having is under the ASP.NET Read Database using the SQLDataReader. When I added the code and ran the program, I got a CS103 code which is The name 'sqlquery' does not exist in the current context. I thought that had to rem out the response.write and ccn.close statements thinking that the connection needed to be opened and still got the same error code. I hoping to find someone who are familiar with this tutorial. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
String connetionString; //Variable declaration
SqlConnection cnn;
connetionString = #"Data Source=BMIS-JHanlon3\SQLEXPRESS;Initial Catalog=DemoDB;User ID=sa;Password=demo123"; //Set connection string
cnn = new SqlConnection(connetionString); //Assign connection
cnn.Open(); //open and close the connection
// Response.Write("Connection Made");
// cnn.Close();
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = " ";
sql = "Select TutorialID,TutorialName from DemoDB";
command = new SqlCommand(sql, cnn);
dataReader = sqlquery.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
}
}
}

Related

command failing in login code in C# on ASP.NET

I am making a website using ASP.NET framework.
My code for login page is as below, it is very simple since I'm trying to see step by step where it is going wrong. The C# code is:
protected void userLogin(object sender, EventArgs e)
{
string encoded_pass = encrypt_pass(Password.Text);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString);
connection.Open();
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password"))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
try
{
cmd.ExecuteNonQuery();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//da.Fill(dt);
////Session["User"] = dt.Rows[0]["user_email"];
//Session["User_name"] = dt.Rows[0]["user_f_name"];
//loginlabel.Text = "Welcome, " + Session["User_name"];
}
catch
{
loginlabel.Text = "login error";
}
}
connection.Close();
}
Now every time I enter an email and password it always gives "login errorr".. Why the command is not executed?
Looks like you have declared the connection but haven't assigned it to the SqlCommand
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password",connection))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
Note i added the connection variable in the cmd declaration.
In future you may also like catching your errors in development:
catch (Exception ex)
{
loginlabel.Text = "login error: "+ ex.Message;
}
This will help you know what is going wrong.

Updating database from ASP.Net getting error "Connection property has not been initialized"

I am trying to retrieve a value from my database, increment it by 1, and then update the database with this new value.
My code so far is
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand("Select likeCount from tbl_Post where tbl_Post.Id="+Convert.ToInt16(content) , conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int oldVal = Convert.ToInt16(dr["likeCount"]);
int newVal = oldVal + 1;
SqlCommand insert1 = new SqlCommand("update tbl_Post set
likeCount="+newVal+ "where tbl_Post.Id=" + content);
insert1.ExecuteNonQuery();
conn.Close();
}
I am getting an error on the line insert1.ExecuteNonQuery
ExecuteNonQuery: Connection property has not been initialized.
The reason of your error is the missing connection in the second command. You can add it to the SqlCommand constructor as you do in the first command, also you have a missing space in the query text for the second command.
These errors and a more serious error called Sql Injection could be avoided if you use parameters like explained in the code below
Least but probably most important is the fact that you don't need two commands to increment the likeCount field. You can write a single command
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
string updateText = #"update tbl_Post
set likeCount=likeCount + 1
where tbl_Post.Id=#id";
using(SqlConnection conn = new SqlConnection(connStr))
using(SqlCommand cmd = new SqlCommand(updateText, conn);
{
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt16(content);
cmd.ExecuteNonQuery();
}
}
Notice also the presence of the using statement around the disposable objects like connection and commands. This allows you to close and dispose these objects also in case of exceptions.

Error occurs when inserting values

protected void Button1_Click(object sender, EventArgs e)
{
string connString = "Data Source=localhost;Initial Catalog=test_db;Integrated Security=True;";
string insertCommand = "INSERT INTO empDetl (empName,addr) values(#empName,#addr)";
string _name = txtName.Text;
string _addr = txtAddr.Text;
using(SqlConnection conn = new SqlConnection(connString))
{
//open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#empName", _name);
cmd.Parameters.AddWithValue("#addr", _addr);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This code doesn't work properly. Please tell me where the error is. While inserting values it says "Invalid object name 'empDetl'" but my table name is empDetl.
You probably have a database security issue here.
"Data Source=localhost;Initial Catalog=test_db;Integrated Security=True;";
This is going to use the current windows user (in the case of a web application probably the IIS user or whatever user your application runs under) to connect to the database using windows authentication.
Although your table may exist, the connecting user may not be able to see it.
Try change your connection string to the same user credentials you are connecting to your DB with through management studio
"Data Source=localhost;Initial Catalog=test_db;User Id=sa;Password=********;";

Database does not exist

Here is my code to back up a database.
These are my databases:
I got this as Error:
Database 'BakupDB' does not exist. Make sure that the name is entered
correctly. BACKUP DATABASE is terminating abnormally.
And the code for my web page:
public partial class Default2 : System.Web.UI.Page
{
string dbname = "BakupDB";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
//Mentioned Connection string make sure that user id and password sufficient previlages
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
//Enter destination directory where backup file stored
string destdir = "D:\\backupdb";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database "+dbname+" to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Response.Write("Backup database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
}
}
What do I wrong?
It looks like you're trying to use a User Instance. As an aside (not 100% related to your question) I believe that this feature is deprecated in SQL Server Express 2012 (and have been on a deprecation path since SQL Server 2008).
Sorry for the aside. With regards to your question perhaps the following will help you:
Stack Overflow question
Accomplishing the task using SMO
I would say the Stack Overflow question is closer to the use case you're trying to achieve with executing the SQL command, but have referenced the SMO way in case you were interested or wanted to try a different approach. Based on the SO question it appears that your connection string:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
Is missing a Database= section so perhaps it should read like:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True;Database=BakupDB";
This code worked for me:
private void button5_Click(object sender, EventArgs e)
{
try
{
string dlink= #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\jsdb.mdf; Database=jsdb; User Instance=True; Integrated Security=True;Asynchronous Processing= True";
SqlConnection dcc = new SqlConnection(dlink);
dcc.Open();
string database = "jsdb";
string blc = textBox1.Text; //(Its the location to save the file)
string nm = "dbBackup";
string dt =DateTime.Today.ToShortDateString();
string sl = "BACKUP DATABASE "+database+" TO DISK = '"+blc+"\\"+nm+"-"+dt+".bak'" ;
SqlCommand cql = new SqlCommand(sl,dcc);
cql.ExecuteNonQuery();
MessageBox.Show("Database backup completed successfully..");
dcc.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}

link data from Textbox to SQL Database in ASP.net (C#)

I am attempting to create a web form where data from several text box's will enter data into a n SQL database I have created. My code is listed below, and the problem is that when it compiles, it acts as if it hasn't. The messagedisplay.text does not change, and the SQL database does not update. Does anyone know a solution?
protected void createButton_Click(object sender, EventArgs e)
{
string state = stateTextBox.Text;
string country = countryTextBox.Text;
string lake = lakeTextBox.Text;
SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO ResearcherID VALUES(#ResearcherFname, #ResearcherLName)", connection))
{
command.Parameters.Add(new SqlParameter("ResearcherFName", country));
command.Parameters.Add(new SqlParameter("ResearcherLName", state));
command.ExecuteNonQuery();
}
messageDisplay.Text = "DB Connection Successfull";
}
catch
{
messageDisplay.Text = "DB Connection Failed";
}
}
try this
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (#ResearcherFname, #ResearcherLName)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("#ResearcherFname", country);
sqlCmd.Parameters.AddWithValue("#ResearcherLName", state);
}
Also use connection.Open(); inside try

Resources