Database does not exist - asp.net

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); }
}

Related

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

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

MS Access database able to be accessed in debug mode but not accessible when published

I've written some basic code in ASP.NET that accesses a Microsoft Access database, which works when I run in debug mode on IIS Express, but when I published the application and tried to run on the actual website, I get the error.
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2430497
NIM_Tool.Default.Page_Load(Object sender, EventArgs e) +2321
System.Web.UI.Control.OnLoad(EventArgs e) +106
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3785
From modifying some of my code, I'm pretty confident that the database is unable to be found, but I can't figure out why it's able to be accessed in debug/release mode but not from the published mode. After clicking publish, all files went to the bin/Release/Publish/ folder from the root directory, which I then copied all the children of the Publish folder to the correct server path. The children files/folder also contained the correct MS Access database.
code from the DataLayer.cs file
public class DataLayer {
static OleDbConnection conn;
static OleDbCommand cmd;
static String connString;
static OleDbDataAdapter adp;
private static void CreateCommand()
{
// have also tried hardcoding this to the production server path but this failed too
connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath("MyDatabase.mdb") + ";Persist Security Info=False;"
conn = new OleDbConnection(connString);
cmd = new OleDbCommand();
cmd.Connection = conn;
adp = new OleDbDataAdapter();
}
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
}
return dt;
}
}
And The Default.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtDeposit = DataLayer.GetDefaultDeposit();
string fixedCost = (string)dtDeposit.Rows[0]["FixedCost"];
}
}
The MyDatabase.mdb file is located in the same directory as the DataLayer.cs file. I've tried hardcoding the database path as well to where it should be accessed on the server, but got the same error message as well.
A little advice: you are being your own enemy when you catch an error and don't do anything with it. It is called "swallowing an error" and it hides root-causes.
Instead, I would recommend doing a re-throw. Put your (original) Exception as the .InnerException. You might want to have your connString in the .Description for the (outer) Exception. (Just in case MapPath didn't do what you thought it should, etc.)
Like this:
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
throw new Exception("ConnString=" + connString, ex);
}
return dt;
}

Error in running simple Web application "System.ComponentModel.Win32Exception: The network path was not found"

I tried to run this code but it raise an error at con.Open() method
"System.ComponentModel.Win32Exception: The network path was not found"
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "server = (localdb)\v11.0 ; database = DepartmentsAndEmployees ; integrated security=true";
SqlConnection conn = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select * from Employees", conn);
conn.Open();
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
conn.Close();
}
}
This is because it can not find the server. There is something wrong with your connection string.
Try this connection string builder:
http://www.developerfusion.com/tools/sql-connection-string/
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

update query is not working in ASP.NET web application

using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=GAGAN-PC\SQLEXPRESS;Initial Catalog=update_test;Integrated Security=True");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void delete_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("delete from update_delete where id like'"+TextBox1.Text+"'",con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully deleted.");
}
protected void update_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update update_delete set password ='"+TextBox3.Text+"' where id like'"+TextBox2+"'", con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully Updated.");
}
}
I am trying to implement update query but there is a little problem in it. I have used SQL Server as database and update_delete is a table in which there are 3 columns id,sname,password and I am trying to update password with respect to id.
Problem is when I click on update button control reaches cmd.ExecuteNonQuery(); no error is displayed. but updating is not taking place. what should I do. Please Please Please help me. Thanks in advance. :) :)
I'm just guessing here - if Id is a numeric datatype, then you cannot use LIKE with it.
Also: please use using()... blocks to ensure proper disposal and use parametrized queries to avoid SQL Injection attacks.
Write your UPDATE command like this:
protected void update_button_Click(object sender, EventArgs e)
{
// get the values to use
string idValue = Convert.ToInt32(TextBox3.Text.Trim());
string password = TextBox2.Text.Trim();
// define the query text with *parameters* !
string updateQuery = "update update_delete set password = #password where id = #ID";
// put things like SqlConnection and SqlCommand into "using()...." blocks
using (SqlCommand updCmd = new SqlCommand(updateQuery, con))
{
// define parameters and their values
updCmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = password;
updCmd.Parameters.Add("#ID", SqlDbType.Int).Value = idValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Data successfully Updated.");
}
}
I suppose you get an Exception. I would kindly suggest to catch your exception and tell us the message... You can catch the exception using the debugger or a try-catch clause.
If you don't get an exception and "Control reached" message is displayed, you would have to use the formed SQL string to use it directly in SQL Server and see if there is a mistake in the SQL statement. I suppose that you somehow form an invalid SQL statement (eg using a non-existing ID).
Hope I helped!

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=********;";

Resources