Unable to access the Microsoft Access database using asp.net and C# - c#

This is code i wrote to add some text to accordion pane on a button click:
protected void Button1_Click1(object sender, EventArgs e)
{
//Use a string variable to hold the ConnectionString.
string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection();
cn.ConnectionString = connectString;
//Create an OleDbConnection object, and then pass in the ConnectionString to the constructor.
//OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString);
try
{
//Open the connection.
cn.Open();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl("Open Error"));
}
string selectString = "SELECT * FROM BasicInfo";
//Create an OleDbCommand object.
//Notice that this line passes in the SQL statement and the OleDbConnection object
OleDbCommand cmd = new OleDbCommand(selectString, cn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
//Note: The OleDbDataReader is forward-only.
try
{
OleDbDataReader reader=null;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception es)
{
AccordionPane1.Controls.Add(new LiteralControl(" datareader"));
}
string s = "s";
reader.Read();
s = reader["S_No"].ToString();
AccordionPane1.Controls.Add(new LiteralControl(s));
//Close the reader and the related connection.
reader.Close();
cn.Close();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl(" Read Error"));
}
}
I have my access 2007 database in the folder i specified in the connectString. When im viewing in the browser, on the button click i am getting all the three exceptions:
What might be the problem in opening the database? Do i need to make any other changes?

Change
Provider=Microsoft.Jet.OLEDB.4.0;
to
Provider=Microsoft.ACE.OLEDB.12.0
Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb
Hopefully it will solve the issue.

you connection string might be cause of isssue
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\abc.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
this For access 2007 also check the path of database is cocrect.

You can use |DataDirectory| instead of real path and you have to change the Provider=Microsoft.ACE.OLEDB.12.0 (as suggested by #MMK)
string connectString = #"Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\Students1.accdb;Persist Security Info=False;";
and always use using block which dispose IDisposable objects properly.
using(OleDbConnection cn=new OleDbConnection())
{
using(OleDbCommand cmd=new OleDbCommand())
{
cn.ConnectionString=connectionString;
cmd.CommandText=selectString;
cmd.Connection=cn;
...
}
}

Related

how to backup and restore mdf file in winform C# after deployment project?

I am developing a desktop application in c# visual studio 2013, where I want to create a feature in which a user is allowed to restore and backup the Database by itself. but problem is that it doesn't backup or restore database after deploy project.
When I try to Backup it says!
Database 'DatabaseName' does not exit.Make sure the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
When I try to Restore Database it says
System.Data.Sqlclient.SqlException (0x80131904): User does not have permission to alter database .mdf', the database does not exit, or the the database in not in a state that allows access checks. and so on!
I am using SQL Server Express 2012 by attaching mdf file to the application, when i try to backup using query it works when i add Connection String through SQL Server but after attach mdf file i won't work .
have watch some tutorial videos and figured out some codes but I got nothing
here is my BACKUP code!
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
String sql = "BACKUP DATABASE neyadatabase TO DISK = '" + backuploca.Text + "\\neyadatabase - " + DateTime.Now.Ticks.ToString() + ".Bak'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show("backup done successfully!");
con.Close();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and here is my RESTORE Code!
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string sqlStmt2 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [neyadatabase.mdf] FROM DISK='" + restoreloca.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am a beginner in this if anyone is going to help me please give some example too so that I can better understand!
Thank you
For backup use :
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConn = new SqlConnection())
{
dbConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
dbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = dbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE neyadatabase SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
dbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE neyadatabase TO DISK='c:\neyadatabase.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And for restore :
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE neyadatabase FROM DISK='c:\neyadatabase.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Backup and restore bak file. Mdf/ldf is for attaching not backup.
I hope this helps you.
If you faced any problem let me know to update my answer ;). Good luck

how to build a SQL connection using C# in Visual Studio 2017?

I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
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();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET

How to kill a SQL Server session or session ID

I'm trying to kill a session in SQL Server 2012 from C# windows Form using kill <spid> but what happens is that when I do that, an error appears:
Cannot use KILL to kill your own process
Code:
// to do DB backup
private void spid2_Click(object sender, EventArgs e)
{
string SQLDataBases;
SQLDataBases = "select ##spid ";
SQLDataBases += "BACKUP DATABASE School TO DISK = \'C:\\Program Files\\Microsoft SQL Server\\MSSQL11.MSSQLSERVER\\MSSQL\\Backup\\AdventureWorks333.BAK\' ";
string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
SqlConnection cnBk = new SqlConnection(svr);
Command = new SqlCommand(SQLDataBases, cnBk);
Command.CommandText = SQLDataBases;
SqlDataAdapter da = new SqlDataAdapter(Command);
DataTable dtDatabases = new DataTable();
try
{
cnBk.Open();
da.Fill(dtDatabases);
label1.Text = dtDatabases.Rows[0][0].ToString();
}
catch (Exception ex)
{
string s = ex.ToString();
MessageBox.Show(s);
label1.Text = dtDatabases.Rows[0][0].ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk.Close();
cnBk.Dispose();
}
}
}
// to kill backup session
private void kill_Click(object sender, EventArgs e)
{
string SQLRestor;
SQLRestor = "Use master; kill " + label1.Text;
string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
SqlConnection cnRestore = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLRestor, cnRestore);
try
{
cnRestore.Open();
cmdBkUp.ExecuteNonQuery();
}
catch (Exception ex)
{
string s = ex.ToString();
}
finally
{
if (cnRestore.State == ConnectionState.Open)
{
cnRestore.Close();
cnRestore.Dispose();
}
}
}
Always use "using" for disposable classes (also to close and dispose), never concatenate string in query, use always parameterized query to avoid sql injection. This is sample how to use SqlConnection, SqlDataAdapter, and SqlCommand :
var connectionString = "...";
var sqlQuery = "...";
// Sample using SqlCommand
try
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("OK, SqlConnection and SqlCommand are closed and disposed properly");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
// Sample using SqlDataAdapter
try
{
var dataTable = new DataTable();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var sda = new SqlDataAdapter(sqlQuery, conn))
{
sda.Fill(dataTable);
}
}
MessageBox.Show("OK, SqlConnection and SqlDataAdapter are closed and disposed properly, use DataTable here...");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
The "Cannot use KILL to kill your own process" is there for a reason. If you're finished using your session, close the connection: SqlConnection is an IDisposable, so wrapping it in an using() {} block will close it automatically when you're done using it. This will return the connection handle back to the pool, and it is up to the SQL server client components to decide whether to keep it around for follow-up connections, or dispose it. SQL server does a good job of managing its process lifecycle and killing them is an administrative option, but nothing that an application in normal operation should do (except for a few reasons, see here)
That said, to answer the actual question: to kill process A, you'd have to open a second connection B and KILL A's process (SPID). This will work as long as the assumption "one SPID = one connection = one session" holds (true for all current SQL server versions).
Furthermore, your user needs the ALTER ANY CONNECTION privilege. This is usually limited to sysadmin and processadmin roles, and your application is unlikely to have this in a production environment.
References:
http://www.sqlservercentral.com/Forums/Topic1503836-1292-1.aspx
http://sqlserverplanet.com/dba/spid-what-is-it

Database connection C#

I have a question according to this code. VisualStudio shows no errors or warnings but when I run it, the result is only the exceptionerror ("Something went wrong."). This is how I have always done it before but somehow always worked except for now. Am I missing a simple thing?
protected void Page_Load(object sender, EventArgs e)
{
// Connect
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb';Persist Security Info=True";
// Execute
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM teachers = ?";// + Request.QueryString["id"];
lbl.Text = "";
cmd.Parameters.AddWithValue("id",Request.QueryString["id"]);
// Read
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lbl.Text = reader["teacherid"].ToString();
}
}
catch (Exception ex)
{
//lbl.Text = ex.StackTrace;
lbl.Text = "Something went wrong.";
}
finally
{
conn.Close();
}
For Detailed info of the Exception,
catch (Exception ex)
{
//Either you can write log or display in label
lbl.Text = ex.Message;
}
Also check the folder access rights for
Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb'
Programmatically to check for specific files use File.Exists(path), which will return a boolean indicating whether the file at path exists.
And validate if the connection has been established or not.

Can't Update Access database File From C#.NET

I try to learn some coding with Visual C#. I create a form for add and update Access database.
I can successfully add to Access file but I can't update them.
I write a code similar below by some search in internet but I get this error:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
My code is:
public partial class form1 : Form
{
private OleDbConnection con;
private void btnUpDate_Click(object sender, EventArgs e)
{
string FirstName = txtFirstName.Text;
string Family = txtFamily.Text;
string City = txtCity.Text;
string approve = txtapprove.Text;
string OfficeNumber = txtOfficeNumber.Text;
string OfficialDossier = txtOfficialDossier.Text;
string Department = txtDepartment.Text;
string Organization = txtOrganization.Text;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Data Source=F:\\Database.accdb");
string query = "UPDATE Sheet1 SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department, Organization=#Organization WHERE OfficeNumber=#OfficeNumber";
//string query = "UPDATE aspnet_Users SET FirstName=#FirstName, Family=#Family, City=#City, approve=#approve, OfficeNumber=#OfficeNumber, OfficialDossier=#OfficialDossier, Department=#Department WHERE OfficeNumber=#OfficeNumber";
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#OfficeNumber", OfficeNumber);
cmd.Parameters.AddWithValue("#OfficialDossier", OfficialDossier);
cmd.Parameters.AddWithValue("#FirstName", FirstName);
cmd.Parameters.AddWithValue("#Family", Family);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#approve", approve);
cmd.Parameters.AddWithValue("#Department", Department);
cmd.Parameters.AddWithValue("#Organization", Organization);
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException)
{
MessageBox.Show("There is a problem!");
}
finally
{
con.Close();
}
}
}
Where I have mistake? I Don't use of DataSet and DataAdapter. Is problem from there?
I'm using VS 2010
Problem 1: You have not Opened the Connection object oleDBConn which was assigned to the OleDbCommand Object.
You have assigned oleDBConn to OleDbCommand object as below:
OleDbCommand cmd = new OleDbCommand(query, oleDBConn);//here you have assigned oleDbConn
but you have opened different ConnectionObject con as below:
con.Open();
Solution 1:
Replace This: You should always Open the OleDbConnection (oleDBConn) Object which was assigned to the OleDbCOmmand Object.
con.Open();
With This:
oleDBConn.Open();
Problem 2: You have created an Extra connection object con (on top of your btnUpDate_Click function) and by mistake you are working with the same.(Opening and closing the wrong connection object instead of proper one)
Solution 2: Remove the extra connection object created on top of btnUpDate_Click function and replace all con occurences with oleDBConn.
Complete Code:
try
{
oleDBConn.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Success!");
else
MessageBox.Show("Sorry!");
}
catch (OleDbException ex)
{
MessageBox.Show("There is a problem!"+ex.ToString());
}
finally
{
oleDBConn.Close();
}

Categories

Resources