I'd like to ask you why doesn't this code work? It goes without any error, even cmd.ExecuteNonQuery(); returns 1 (is it if changes one row in the database), but in the actual database, there's absolutely no change. With other database tables, this code works properly, but I'm also not able to remove a row from this table - it behaves asi it if was "read-only", but I have no idea why - yesterday, everything worked fine and now, it's suddenly stopped working :-(
string sConnectionString;
sConnectionString = "Data Source=.\\SQLEXPRESS; AttachDbFilename=\"" + zdielaneInfo.Adresar + "\\rozvrh.mdf\";";
sConnectionString += "Integrated Security=True;User Instance=True";
SqlConnection objConn
= new SqlConnection(sConnectionString);
objConn.Open();
SqlCommand cmd = new SqlCommand("", objConn);
if (zdielaneInfo.Edit)
cmd.CommandText = "UPDATE subject " +
"SET name = #name, day = #day, timeStart = #timeStart, timeEnd = #timeEnd "
+ "WHERE id = #id";
else
cmd.CommandText = "INSERT INTO subject (name, day, timeStart, timeEnd) " +
"Values (#name, #day, #timeStart, #timeEnd)";
cmd.Parameters.Add(new SqlParameter("#name", txbName.Text));
cmd.Parameters.Add(new SqlParameter("#day", dniNaInt(cbDen.Text)));
cmd.Parameters.Add(new SqlParameter("#timeStart", DateTime.Parse(txbStart.Text)));
cmd.Parameters.Add(new SqlParameter("#timeEnd", DateTime.Parse(txbEnd.Text)));
cmd.Parameters.Add(new SqlParameter("#id", zdielaneInfo.Id));
cmd.ExecuteNonQuery();
objConn.Close();
Your problem looks like mdf file overwrite problem.
You are accessing mdf files that are put in the debug folder and replaced every time you run the application.
Be sure that in your project, if you have the database attached within your solution that you are not overwriting it. So select the mdf file in your solution explorer and make sure that its "Copy to output" is set to "Do not copy", then manually copy over the mdf file to the project\bin\debug folder then run the application.
Hope it helps.
Maybe the table is locked.
From HERE, try this:
select
object_name(P.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks L
join sys.partitions P on L.resource_associated_entity_id = p.hobt_id
If your table is in the result set you have your answer.
Another possibility is the user that you are using to run. Maybe he got privileges revoked.
STOP using the user instance / attachdbfilename options (user instance is deprecated!). Create your database on a real SQL Server, then connect to it directly with your connection string. Using this deprecated feature means that every time you start up your program you're starting with a new copy of the database, and what you inserted yesterday is no longer there - and if you connect to the database using that connection string from two different applications, one is not going to see the data that the other one is changing.
Related
I've created a simple Windows Forms application in C# and now find it hard to connect it to a SQL Server database. I've created the database within Visual Studio itself. However, once I try to insert data I get a SQL exception. My guess is there is problem in the connection data source i.e the con variable. Please help me find a solution.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Database1;Integrated Security=SSPI");
SqlCommand cmd;
SqlDataAdapter adapt;
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
cmd = new SqlCommand("insert into [dbo].[user] (Id, username, password) values (#id, #name, #state)", con);
con.Open();
cmd.Parameters.AddWithValue("#id", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
cmd.Parameters.AddWithValue("#state", textBox3.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else
{
MessageBox.Show("Please Provide Details!");
}
The database file name is
\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf
If you created the database on an actual instance of SQL Server (this can be a local instance on your machine), it appears as though your connection string's data source isn't quite right.
Data Source=DESKTOP-XXXXXXX/Shenal Burkey
There are two problems with this, first the slash (/) should actually be a backslash (). Second, after the slash you have 'Shenal Burkey' with a space. SQL Server instance names cannot contain space characters. That being said, if you installed SQL Server as a named instance, you need to specify the named instance in that place, if you accepted the default instance name it should be 'MSSQLSERVER'. If you are using the default instance name, you can either specify your connection string like this:
Data Source=DESKTOP-XXXXXXX\MSSQLSERVER
or you can omit the instance name entirely and just use:
Data Source=DESKTOP-XXXXXXX
Also, just a tip, you will notice I replaced the specifics of your DESKTOP's hostname with X's, personally I'd recommend editing your question and doing the same. It may not seem like it would be useful, but someone might just pick that up and find a crafty way to do some damage. Better safe than sorry.
I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?
I'm trying to use a MS Access database in C# using OLE DB, but every time the database loads it does not keep the old data.
This is my code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Databases\\Database.accdb;Persist Security Info=False;";
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO test (userID, name) VALUES(?, ?)";
// Setting parameters to random integer and string
command.Parameters.Add(new OleDbParameter("#userID", randomID));
command.Parameters.Add(new OleDbParameter("#name", randomName));
command.ExecuteNonQuery();
For testing purposes I use a randomly generated ID and name. If I check the database in MS Access the data is overwritten every time. Am I missing something?
I use this code for creating the table:
OleDbCommand command = connection.CreateCommand();
command.CommandText = "CREATE TABLE test (" +
"userID INTEGER NOT NULL," +
"name TEXT(20) NOT NULL," +
"PRIMARY KEY(userID)" +
")";
command.ExecuteNonQuery();
This typically is associated with the properties of the Database.accdb file as it exists in Visual Studio.
By default, the "Copy to output directory" field for the file is set to "Copy always". So, this means that every time to launch the application in Visual Studio, it will completely replace the working copy of Database.accdb with the prototype version.
So, the solution is kinda simple... change the field to "Copy if newer" (or "Do not copy")
I have a C# winforms application connected to a localDB in Visual Studio 2012.
When i run the application for the first time i can add a record with the code below.
SqlCommand com = new SqlCommand();
com.Connection = new SqlConnection(Properties.Settings.Default.BioEngineering);
com.Connection.Open();
com.CommandText = "INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES (#Forename,#Surname,#Company,#SecurityLevel,#IssueDate,#ExpiryDate,#CardID)";
com.CommandText = "INSERT INTO SignInOut (UserID) VALUES (#UserID)";
com.Parameters.AddWithValue("#UserID", this.txtMemberId.Text);
com.Parameters.AddWithValue("#Forename", this.txtFirstName.Text);
com.Parameters.AddWithValue("#Surname", this.txtLastName.Text);
com.Parameters.AddWithValue("#Company", this.txtCompany.Text);
com.Parameters.AddWithValue("#SecurityLevel", SecurityLevel);
com.Parameters.AddWithValue("#IssueDate", this.dtpIssueDate.Value);
com.Parameters.AddWithValue("#ExpiryDate", this.dtpExpiryDate.Value);
com.Parameters.AddWithValue("#CardID", this.txtCardId.Text);
com.ExecuteNonQuery();
com.Connection.Close();
MessageBox.Show("New Member has been added!");
this.Hide();
mainMenu.Show();
Now, it shows this one record, but when i go to add a second record through the winforms, it says it is updated, but when i go to view the LocalDB it still only has the first record. Ive spent all trying to figure it out, i also have output set to not copy since it cause problems in the bin DB, which i dont want, i want it to update directly to the localDB? i refreshed as well, any ideas???
Any more information can be provided upon request.
I am using asp.net for my project , and I am using the following code , but its not working correctly
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\WEB_PROJECT\\App_Data\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE info SET fname = #fn, lname = #fl, phone= #ph, recoveryq=#rq, recoverya=#ra WHERE username = #un";
cmd.Parameters.AddWithValue("fn", TextBox3.Text);
cmd.Parameters.AddWithValue("fl", TextBox4.Text);
cmd.Parameters.AddWithValue("ph", TextBox5.Text);
cmd.Parameters.AddWithValue("rq",TextBox6.Text);
cmd.Parameters.AddWithValue("ra",TextBox2.Text);
cmd.Parameters.AddWithValue("un",line);
cmd.ExecuteNonQuery();
con.Close();
Advice plzz i m confused !!! :(
As I've said before on this site - the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your UPDATE works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the con.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. ASPNETDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=ASPNETDB;Integrated Security=True
and everything else is exactly the same as before...
cmd.Parameters.AddWithValue("#fn", TextBox3.Text);
You have to specify the parameter name along with '#' .