There is no record in the Table - SQL C# - c#

I'm having a problem with SQL. I'm new to C# so I don't really know what to do.
Here's the code:
public static void addMemo()
{
schedule sch = (schedule)Application.OpenForms["schedule"];
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\_data\schedData.mdf;Integrated Security=True"))
{
SqlCommand CmdSql = new SqlCommand("INSERT INTO schTable (evnName, evnDate, evnTime, evnStatus) VALUES (#evnName, #evnDate, #evnTime, #evnStatus)", conn);
conn.Open();
CmdSql.Parameters.AddWithValue("#evnName", sch.txtName.Text);
CmdSql.Parameters.AddWithValue("#evnDate", sch.txtDate.Text);
CmdSql.Parameters.AddWithValue("#evnTime", sch.txtTime.Text);
CmdSql.Parameters.AddWithValue("#evnStatus", "Upcoming");
CmdSql.ExecuteNonQuery();
sch.lblNotifier.Text = sch.txtName.Text + " Added.";
conn.Close();
}
}
Everything works fine, there are no errors. But when I looked into the table, there was nothing. I cannot see my inputs. Can someone help me?
EDIT - Here I have a working code that I made before in VB.Net I'm trying to use this instead but I'm stuck with the Tables part. (I'm a noob at c#)
Private ConStr As New String("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\data_\database.mdf;Integrated Security=True")
Dim MyNewRow As DataRow = SqlDatTbl.NewRow()
SqlDatTbl.Rows.Add(MyNewRow)
SqlRowPos = SqlDatTbl.Rows.Count - 1
SqlCon.ConnectionString = ConStr
SqlCon.Open()
SqlDatAdp = New SqlDataAdapter("Select * from Events", SqlCon)
SqlCmbBld = New SqlCommandBuilder(SqlDatAdp)
SqlDatAdp.Fill(SqlDatTbl)
If SqlDatTbl.Rows.Count <> 0 Then
SqlDatTbl.Rows(SqlRowPos)("Name") = txtName.Text
SqlDatTbl.Rows(SqlRowPos)("Date") = txtDate.Text
SqlDatTbl.Rows(SqlRowPos)("Time") = txtTime.Text
SqlDatTbl.Rows(SqlRowPos)("Status") = "Upcoming"
SqlDatAdp.Update(SqlDatTbl)
MsgBox("New Event Added")
End If
SqlCon.Close()

When working with an attached database and that database is being shown in Solution Explorer there is a property, "Copy to output directory" where the default setting is "Copy Always". So if you were to assign a variable to ExecuteNonQuery and the results show a value higher than 0 then you will need to set "Copy to Output Directory" to "Do not Copy" and then manually copy the database into the Bin\Debug or Bin\Release folder or set "Copy to Output Directory" to "Copy if Newer" which means unlike "Copy always" this value will only copy the database to the app folder if you make any changes to the database in the project folder. I have a article with samples and explanations for you to try out MSDN Working with Copy to Output Directory.
Here is the default setting
If ExecuteNonQuery returns 0 then the above is not the issue.

Have you checked to make sure that sch.txtName.Text and sch.txtDate.Text and sch.txtTime.Text actually have values in them? Insert a breakpoint on conn.Open(); and then if you mouse over sch.txtName.Text, sch.txtDate.Text, and sch.txtTime.Text in your code, then it should show a little tooltip with information about the field you are mousing over. Here's an image showing what it looks like for me with a chunk of some random code. The popup has an arrow on the left side that opens up if you mouse over it. That'll give you more information about the variable you are looking at. If your text values are empty, then it has nothing to write to the database. Depending on how the database is configured, that could mean that it doesn't write anything at all or that it writes empty fields.
Since you said you are new, if you don't know how to add a breakpoint, you can add one in visual studio by right clicking on the line you want to put the breakpoint at and then under the breakpoints sub-menu, click on Insert breakpoint. Now when you run your code in debug mode and it gets to that point, it will stop and let you see what's going on.

Related

Button not updating the database

I want to give the users to the ability to update their info on database. I made the button to for the software to take the name from one of the textboxes and send it to the database.
public void Updatebtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update Users set First_Name=#fn WHERE ID = '2' ", con);
cmd.Parameters.AddWithValue("#fn", UFirstName.Text);
cmd.ExecuteNonQuery();
con.Close();
}
I watched a YouTube video and followed step by step. But it didn't work.
The button works and executes command. But something is wrong with either sql command or connection because the database doesn't get updated
because your codes seems okey to me with no problems in it i'll give you some tips that will make sure you almost avoiding most mistakes biggeners like me did which caused unexplaind errors.
these tips will REALLY REALLY help you in your programming journey.
when adding a new local database, create a newfolder and name it DataBaseFolder as an example inside your project folder , so you always know where is your database and you dont get confused about other databases in the default location VS saves them, and its better that the project folder is placed in the partition "C" in a default folder of windows.
when creating a new table, name it probably in the definition part at the bottom where you can see:
create table [dbo].[TableName] then press Ctrl + s, make sure to save that table in the same folder as your database, so you always know this table is for this project.
)))) each time you update your table definition like column name or type, or adding a new column or deleting an existing one, make sure to press Ctrl +s and save the table (replace) in the same folder you originally created it, that will make sure you don't get the error most new developers like me were stuck at which is the update window is taking forever to preview the changes.
))))) to make it easy for myself to use the sql commands, i created a script (class.cs) and put the important codes in methods with parameters so i save a lot of time when i was restarting over my program because of some mistakes i did :D
first i defined my sql connection in the class named SqlCodes:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
then i created my methods, examples:
public void QueryCommand(string QueryString)
{
con.Open();
SqlCommand cmd = new SqlCommand(QueryString, con);
cmd.ExecuteNonQuery();
con.Close();
}
public void FillingDataGridView(parameter1,parameter2, parameter3)
{
con.Open();
some code;
con.Close();
}
So, back to my main class where my button will function:
SqlCodes sqlCodes = new SqlCodes();
in the button i now can write:
sqlCodes.QueryCommand("insert into MyTable values (your values)");
or
sqlCodes.RefreshDataGridViewAfterEntry (parameter1,parameter2,parameter3)
or
string queryCommand = " insert into MyTable values (your values)";
sqlCodes.QueryCommand(queryCommand);
or in the load form method so when you open the program it shows the data you want instantly
{
sqlCodes.FillingDataGridview(parameter1,parameter2,parameter3)
}
if you're having errors with your database, don't delete the files you will find in the solution explorer because it will cause you some errors i couldn't figure their solution, just delete the database in the server explorer, and don't forget to change the sql connection path in the SqlCodes Class you created.
that will save you time and and to avoid errors and make your code very simple, instead of copy paste/ writing about 7 or 8 lines each time you want to do something with your database.
I managed to solve the problem.
As it Turns out. clicking the button also calls page_load. Which has a code that replaces text in the textbox. So the button would first call page_load. Retrieving data from the databox. Then it would put in the textbox.
Then it would take data from the same textbox again and send back it to the database.
I managed to fix it by putting the code in pageload inside in if statement. And then i put !Page.IsPostBack condition inside the if statement.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Active"] != null && Session["Active"].ToString()
=="Yes" && !Page.IsPostBack)
{
GetUserData();
}
}
Hope that helps.

Changes do not get saved permanently into SQL Server Compact edition

I am having a weird problem. I am using vs2012 to connect to SQL Server CE and executing some insert queries.
public void EstablishConnection()
{
connection = new SqlCeConnection("Data Source=DataDump.sdf;Persist Security Info=False;");
try
{
connection.Open();
Console.WriteLine("Connection Successful");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
public void AddRecord(string link,string content)
{
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) VALUES('"+link+"','"+content+"');",connection);
num = command.ExecuteNonQuery();
Console.WriteLine("Command Successful rows affected"+num);
var cmd2 = new SqlCeCommand("SELECT * FROM Webpages",connection);
SqlCeDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
Console.WriteLine(reader[1]);
}
}
However I am having the problem that once VS is closed and when later I open it to display the data, the data is gone as it was never saved
How is that possible when it is clear then it executed the query?
It is a common scenario.
You have your database file listed between your project items.
Its property Copy to Output directory is set to Copy Always.
Now, you run your debug session with VS. The compile is succesfull and VS copies your sdf file from the project folder to the current output directory (BIN\DEBUG).
Your code runs smoothly and inserts the data in your database file (on the output directory).
You stop and restart the debug session to fix something, but, at restart, the VS recopies the empty file from the project folder to the output directory.
To break this circle, set Copy to Output Directory to Copy Never (or Copy if Newer)
EDIT Another source of confusion is due to the use of SERVER EXPLORER to view the contents of your database file. If the server explorer use a connection string that points to the database file in the project folder you never see the changes made to the database file in the Output Directory.
You should create two connections in Server Explorer, one named DEBUG DataDump that points to PROJECTFOLDER\BIN\DEBUG. You could use this connection to check the data inserted during debug or for other debugging tasks. Another one, called DISTRIBUTION DataDump, points to the file in the project folder and you make here your schema changes needed for the distribution of your app.
Said that, keep in mind that your code has a BIG problem. It is called Sql Injection
A parameterized query will avoid quotations problems and remove the Sql Injection
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) " +
"VALUES(#lnk, #cnt)",connection);
command.Parameters.AddWithValue("#lnk", link);
command.Parameters.AddWithValue("#cnt", content);
num = command.ExecuteNonQuery();
set Copy to Output Directory property as Copy if newer for your sdf file
it seems now you have set it as copy always which result :
The database file is copied from the project directory to the bin
directory every time that you build your application. Any changes made
to the data file in the output folder are overwritten the next time
that you run the application.

INSERT INTO command not working

Before I start, I'll let you know that I tried everything that has already been suggested on previous questions and other websites before I considered posting a question myself. As it happens, nothing seems to work and I'm just about fed up with this.
As some background information, this is for my Computing A2 project, so I'm kind of stuck for time now - i.e. I can't be changing loads of my code ideally.
Anyway, onto the issue...
I'm using SQLCe in my code to read from various tables and write to one. So far, the code for reading from the tables works fine, so that's any connection issues out the way first. The piece of code I am struggling with is as follows:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
This is just one of the many ways I have tried to combat the issue I am having. I have also explored:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
to pass the parameters...and another method which escapes me now (using ".Value = StaticUser.StudentUser.username" I think). Furthermore, I have tried using a 'using' statement for the command to save me closing the connection myself (I will probably end up using a solution that uses 'using'). Finally (albeit this isn't a chronological recollection), I tried:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)", myConnection)
Again, of course, to no avail.
To highlight the actual symptoms of the issue I am having: The code appears to run fine; stepping through the full method I have pasted above shows that no error is being caught (of course, the message box does not appear - I realised afterwards that stepping through was arguably an unnecessary procedure) and in the other methods I have touched on, the same thing happens. The issue, then, is that the table 'bookings' is not actually being updated.
So, my question, why?
I didn't do the obvious and check the Debug folder for an updated database.
Look for a copy of the database file in your bin/debug folder.
Use full path in connection string, and preferably do not include the sdf file in your project (or at least set build action to None)
i think you are not defining a connection for the command
try
mycommand.connection = connectiostring;

OleDbCommand.ExecuteNonQuery() does not save changes in ms access database

I have .mdb database, and code like this:
using (OleDbConnection connection = new OleDbConnection(myConnectionString))
{
using (OleDbCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE myTab SET col2 = #val1 WHERE col1 = #val2";
cmd.Parameters.AddWithValue("#val1", 0);
cmd.Parameters.AddWithValue("#val2", -1);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
I get data from db, change it in my gui programm, then save it in db. Changes saves, but not in db (I don't know where), so when I run program, change data, close program, then again run - changes remain, but when I open db (not in programm), there are no changes saved, and again run - all changes disappear.
PS: when I commit changes, then run program several times, all changes disappear too, after (3-4 runs)
When we we add .mdb in project root in VS ,when change structure ,VS default delete .mdb file in debug folder and replace new file; now you can change this defult :
1- right click .mdb file and select option
2- set Copy To Output Directory to Do Not Copy
It is most likely the WHERE clause of your update statement isn't locating any records to update.
http://weblogs.asp.net/stevewellens/archive/2009/10/16/why-sql-updates-fail-three-reasons.aspx

MS Access DB doesnt save changes after execution (C#)

I have the following code for using an access database
OleDbConnection con = new OleDbConnection(myproject.Properties.Settings.Default.myDBConnectionString);
con.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO components (name) VALUES (#p_col1)", con);
command.Parameters.Add("#p_col1", OleDbType.VarChar).Value = "test row";
int rows = command.ExecuteNonQuery();
At this point rows value is 1 and when I make select queries after that the row inserted is available. The problem comes when the program finishes: in further executions that row isn´t there anymore.
I´ve tried with transactions
OleDbTransaction transaction = con.BeginTransaction();
command.Transaction = transaction;
transaction.Commit();
and using DataSets and ADO this way
//... add row to dataset ...
OleDbDataAdapter sda = new OleDbDataAdapter("select * from components", con);
OleDbCommandBuilder cb = new OleDbCommandBuilder(sda);
sda.Update(ds.Components); //tried with ds.Components.AcceptChanges(); before and after this line
but in every case i have the same problem, seems like the insert query is not done in the real database. Do you know why can this be happening???
Thanks in advance
Is the database in your bin directory? Is it also part of your project? I have seen this happen when every time you build it overwrites the database in your bin directory with the one from the project directory, so it appears things are not getting saved.
There may be more than one database and you are not inserting to the one you think you are inserting to.
MS Visual Studio builds the Access DB into the product.
--- The product is located in your bin directory.
--- To view any and all changes to your DB via application use this one
When you initially add the DB to the project, it is set to always update the product on build.
This can be a good thing, but I find it rather annoying.
In order to fix this:
Select the MS Access DB from your Solution Explorer,
Hit F4 to go to it's properties,
Change the field "Copy to Output Directory" to "Copy if newer" instead of "Always".

Categories

Resources