Getting a database error when trying to view data - c#

Alright,
I have a page that interacts with my SQL data connection. it tries to run a stored procedure, but every time I run it, it locks out of the database showing this error:
Here's the code the fires of the connection and stored procedure `
FileUpload1.SaveAs(Server.MapPath("images//" + FileUpload1.FileName));
string Image = MapPath("images//" + FileUpload1.FileName);
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;
}`
Any help is appreciated and always thank you!

Try moving your mdf file out of OneDrive. Sometime when OneDrive is doing an upload, or one of the many other processes it does, it will lock the files - especially from system user.

It is saying that your database is under usage so you can not access it.
Be sure that no other code is accessed in the database without closing the connection.
You may also update the code with the following as some not needed lines are removed.
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;

You already have the file open but just don't know it. For example, if you are trying to open a text file called Test.txt (or conversely a .mdf database file which has already been opened), then you will get this error, which is also why you are likely getting the other errors down the line but all related to this first error.
With databases, things can get a bit tricky, because you can connect to a database and at times get an error and be kicked out of the system without closing the connection or process... at which point a currently running but unknown process may be keeping the connection alive. You can look at all open processes on your system or see if you mistakenly have the connection open and then close it before trying to open it through the application.

Related

Created a login form with a local SQL database, upon execution and after a login attempt an "ArgumentException Unhandled" error occurs

I understand the same thing has been asked before and closed due to a simple typo. From what I can see I don't have any typos and I've tried to figure out the problem by Googling but no luck.
I have created this Login Window.
Main Login Window
I have created a local SQL Database from within Visual Studio (2015) to store my users. To establish the connection to this database I have written this line of code in my Enter button that is visible in the Main Login Window.
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C: \USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
This path has been pasted by right clicking my database and selecting properties. In the properties there is a field named Connection String. That's what I have copied and pasted, into the above path in the code.
This is all my code.
//Find path for SQL Connection
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
//Add query for actions to be taken once connection is established, select the user
string sqlQuery = "Select * from dbo.Table Where username = '" + txtEnterUserName.Text.Trim() + "' and password = '" + txtEnterPassword.Text.Trim();
//Add SQL Data Adapter passing in the connection and the query
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, sqlConn);
//Create new Datatable object
DataTable dataTable = new DataTable();
//Fill SQL Data Adapter with the dataTable
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count == 1)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
When I run the program, my Main Login Window appears as it's the main window, I enter my credentials as per the table in the database and I get this error as soon as I press the "Enter" button.
ArgumentException was unhandled
I have checked and rechecked the path but I can't seem to get it working and I have no idea what the problem is. General Google searches have not helped.
Due to low reputation as I am a new user, I cannot upload my table data, I only have one row with a user name and a password. Presume these are being typed correctly.
The error says that a keyword is not supported. I can't seem to understand this.
EDIT. I have reinstalled the server and the new path is now
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))
as per the new Connection String. So the new code for the Enter button is now
private void enterButton_Click(object sender, EventArgs e)
{
string sqlQuery = #"Select * from dbo.Table
Where username = #user AND
password = #pass";
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlConn.Open();
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
}
}
}
The new error I have is {"Incorrect syntax near the keyword 'Table'."} and the error points to this line.
using (SqlDataReader reader = cmd.ExecuteReader())
There are many errors in your code.
The first one is the space between the C: drive letter and the remaining path is wrong and should be removed. Also adding a semicolon in the middle of the connection string as part of the path confuses the connectionstring parser that uses the semicolon as separator between keys and values. This is the origin of the error message because after the NIKOS(); semicolon the parser ends its discover of the path and tries to make sense of \SAFE BOX.... as it was a key to parse.
You should remove it from your disk path and adjust your connectionstring
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;
Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS\SAFE BOX\DATABASE\SAFEBOXDB.MDF;
Integrated Security=True;
Connect Timeout=30;
Encrypt=False;
TrustServerCertificate=True;
ApplicationIntent=ReadWrite;
MultiSubnetFailover=False");
Now the problems in code are even worse
string sqlQuery = #"Select * from [Table]
Where username = #user AND
password = #pass";
using(SqlConnection sqlConn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlConn.Open();
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();
using(SqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
}
}
First of all, you don't need a complex SqlDataAdapter if you just want to check if the user exists or not. A simple SqlCommand with an SqlDataReader will do just fine.
Second, all disposable objects should go inside an using statement to be sure that when you have finished to use them, they will be destroyed also in case of exceptions.
Finally, parameters are always the way to go when you need to pass values to your database. Failing to use them will lead to Sql Injection attacks or unexpected syntax errors when your strings contains single quotes.

How to restore back up programmatically

I created a backup on button click
My code for this is
con.Open();
string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
Now I would like to restore the backed up database, please help I searched lots of questions, but I didn't get the answer I need - please help me to perform this task.
I tried to restore using this code:
string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.ExecuteNonQuery();
}
con.Close();
but I am getting an error
Please help me with this
Each of the physical files needs to reside somewhere on the system that you're attempting to restore the backed up database to. The error message is telling you that the files are in use by another database. You can query sys.master_files to find out which database they belong to.
To resolve this, you need to either delete the database that is using those physical files or add a MOVE clause into your RESTORE statement. For the latter, it would look something like this:
RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';

How to add items to existing database thru application form

I currently have a dataset and would like to continually add new items to that dataset (like type a new entry in a textbox and add it with a button) and edit current items via the applications form I created.
How would I go about tackling this issue?
edit:
This was the best base start I could come up with watching videos and going through google. Dictionary.mdf is my dataset
SqlCommand cmd = new SqlCommand("insert into dictionary(word, definition) values(#word, #definition)");
cmd.Parameters.AddWithValue("#word", textBoxWordtoAdd.Text);
cmd.Parameters.AddWithValue("#definition", textBoxDefinition.Text);
this.Close();
I think you are missing the cmd.ExecuteNonQuery();
If you were using Ms Sql Server. Then your code should look something like this:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string sql = "insert into dictionary(word, definition) values(#word, #definition)";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.Add("#word", SqlDbType.Varchar, 50).value = textBoxWordtoAdd.Text;
cmd.Parameters.Add("#definition", SqlDbType.Varchar, 50).value = textBoxDefinition.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
You also need to open a conneciton which I don't see in your code, but I assume you do it somewhere. Just replace the ConnectionString in the code with your own connection string.

ADO.Net c# 0x80131904 must declare scalar variable/function

I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
SqlConnection connection = Database.GetConnection();
DataTable dt = new DataTable("CRC");
SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(#RentalStartDateTime,#RentalEndDateTime,#CarTypeID)", connection);
try
{
connection.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
cmd.Parameters.Add("#RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
cmd.Parameters.Add("#CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
connection.Open();
Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show("The rental change is: " + rentalChange.ToString());
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
}
connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.

Can't connect to database (OCIenVCreate has failed)

I'm using an Oracle database(10g) which contains a stored procedure called Foo.
Foo takes 2 datetime as IN parameters and 1 cursor as OUT parameter. I've been trying to make the connection and the query to the database with the OleDbCommand, but since Foo needs a cursor I have no choice but to use a OracleCommand(right?).
When I try to connection to the database I get the following error : "OCIenvCreate has failed return code -1". I've gived the correct permissions to ASPNET user for the oci.dll file so that it can read and execute it. Unfortunately, I still get the same error and I'm lost.
Here is what cause the error
OracleConnectionStringBuilder conBuilder = new OracleConnectionStringBuilder();
conBuilder.DataSource = dataSrc;
conBuilder.UserID = user;
conBuilder.Password = password;
OracleConnection con = new OracleConnection(conBuilder.ConnectionString);
OracleCommand cmd = new OracleCommand("foo", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("this_is_a_cursor", OracleType.Cursor).Direction = ParameterDirection.Output;
con.Open(); // Cause the error at runtime
OracleDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
I've noticed that some other people are having the same problem.
I'm running the application from a Windows Server 2003 Entreprise Edition(I hope this can help).
Thank you.
I'm not quite sure what the exact problem was, but I managed to connect to my database with another provider in the connection string.

Categories

Resources