Local SQL DB Insert fails, no error given - c#

I'm trying to insert a record into a table in a local SQL DB using Visual Studio 2015. The code never returns an error, but yet the record is never actually inserted.
try
{
conn.Open();
SqlCommand inscmd = new SqlCommand();
inscmd.Connection = conn;
inscmd.CommandText = "INSERT INTO Attendance (StudentID,DatePresent) VALUES (#StudentID, #DatePresent)";
inscmd.Parameters.AddWithValue("#StudentID", intStudentId);
inscmd.Parameters.AddWithValue("#DatePresent", DateTime.Now.ToString());
inscmd.ExecuteNonQuery();
MessageBox.Show(((ExtendedButton)sender).Text + " has been marked as present.");
conn.Close();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
When I run the code, the message box pops up stating that the student has been added to the attendance record. When I close the app to look at the actual data in the table, though; that data is not present.
My "Catch" message box never appears.

If the ExecuteNonQuery returns 1, that means it has affected 1 row. So, it looks like the command is working and something else is occurring. Either you're not looking at the right place, or the right table or something; or the row is being deleted by either a trigger that removes it, or a rollback transaction later on - either explicitly or implicitly. You could try explicitly committing before closing.
So, you need to check further into your code or DB.

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.

incorrect syntax in c# sql command

I've got the following
SqlCommand cmd = getSQLCommand();
using (cmd.Connection)
using (cmd)
{
try
{
string dbName = txt_DatabaseName.Text;
var createDatabaseQuery = "exec ('CREATE DATABASE ' + #databaseName)";
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
sqlCommand.Parameters.Add("#databaseName", SqlDbType.Text);
sqlCommand.Parameters["#databaseName"].Value = dbName.ToString();
cmd.Connection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('SQL Error. Record not added.')", true);
}
finally
{
cmd.Connection.Close();
}
}
I'm fully aware that params are not supported in DDL operations, so I've got this really cool thread that I've been using to help me write the contents within the "try".
How to use SqlCommand to CREATE DATABASE with parameterized db name?
That said, I'm still getting an exception error for incorrect syntax near 'Database'. This might be a user error but I've been stuck around this for an hour or so now.
Any thoughts/ improvements?
p.s. All I'm trying to do is to create a database programmatically by using a dynamic value of whatever happens to be in txt_DatabaseName.Text (and yes I will try to error handle this in case there's white spaces entered or any chars that are not supported in SQL.
p.p.s Any articles that I can have a look at against sql injection attacks or any suggestions around constructing the method I have to prevent it? This is a simple exercise that I'm doing on my local machine, not public facing but still would like to get ahead of the game if possible.
You don't need the exec part at all. Again you are getting error after removing exec cause you are wrapping your query in single quote 'CREATE DATABASE ' which is getting considered as string literal. It should just be
var createDatabaseQuery = string.Format("CREATE DATABASE {0}",DBnamevariable);
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
Take a look with the sql profiler to see what is being fired against the database. If it is not working try to execute the query in Management studio to see it that is working. It's probably some kind of special character that is not allowed.

C# MDF database is not inserting data even if success message is displayed

I need to insert data when user clicks. But, my code isn't doing it. Even though it displays the data inserted message, the data is not inserted. How can I find the mistake?
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=**F:\Blackhat\Blackhat\Blackhat.mdf**;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert Into Clients(name) VALUES ('"+clientname.Text+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Success "+clientname.Text);
con.Close();
}
catch (SqlException ex)
{
MessageBox.Show("Failed"+ex);
}
}
Since there are no exception, the issue would be like, you are writing it to a wrong file in a wrong location or something of that sort.
If it fails to write, there will be an exception and it goes to the catch block.
So we can expect that there are nothing wrong in the c# code.
If you are checking the entries using SQL server management studio, you need try querying the database. The edit 200 rows option needs a database refresh and edit again after closing the existing edit tab. else the vales do not appear to be changing.
Hope this helps. If the issue is something else, please mention in the comments.

Need to when ExecuteNonQuery has finished before proceeding to next line of code

I searched and checked but did not see what I need. I am using a data adapter's UpdateCommand's ExecuteNonQuery to update a local Access database. When I run the code, the ExecuteNonQuery does not appear to finish before the next line of code is executed and therefore, the updated database is not reflected in my grid or my text boxes. If I put a messagbox right after the ExecuteNonQuery, then when I hit ok in the messagebox, the rest of the code is executed and the updated database is reflected in my grid and text boxes. Or if I step through the code in debug without the messagebox to hault execution, the update to the database is reflected on my form. But if I just run the code without something after the query to slow it down or stop it, the update is not shown in my controls.
OleDbConnection connection = new OleDbConnection(connString);
string sql = "Update Table1 set Country = '" + txtNewText.Text + "' where SomeNum =
1111";
connection.Open();
dAdapter.UpdateCommand = connection.CreateCommand();
dAdapter.UpdateCommand.CommandText = sql;
dAdapter.UpdateCommand.ExecuteNonQuery();
//MessageBox.Show("Pause");
dTable.Clear(); //Clear or it will add everything to what was there.
dAdapter.Fill(dTable);
row = dTable.Rows[0];
txtCompany.Text = row["Name"].ToString();
txtGenre.Text = row["Job"].ToString();
txtId.Text = row["Id"].ToString();
txtSomeNum.Text = row["SomeNum"].ToString();
txtCountry.Text = row["Country"].ToString();
I'm assuming that the update query is not finishing before I re-fill the data table. Can someone please help me with this. I looked for something to show the status of the update query but did not see what I need. What am I missing here???
Thank you!
VH
10/28/14 Last night I added dAdapter.UpdateCommand.ExecuteNonQuery() right after dAdapter.UpdateCommand.ExecuteNonQuery(); then everything worked. I was not sure if this was just something that took enough time to allow the query to finish and therefore causing the update to display, or if it was just some fluke "band-aide" that worked. I then replaced that with connection.Close(); and that worked as well. Again...I don't know if closing the connection caused the query to finish and the connection to close before moving to the next line of code, or if this was also just "fudging" it to work. I have seen other people having similar problems in my searching for answers but I have not seen any one explain what the problem is and why this happens or the most appropriate solution.
You should use the OleDbDataReader, since you aren't using SQL.
Provides a way of reading a forward-only stream of data rows from a data source.
An example:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
}
This will iterate through each specified column allowing you to fill your data. Documentation can be found here.

Can't Create The Same Table Twice in SQL Server

i have a C# Windows Form Application. I push a button it should create a Table and insert a value (int).
I create the initial database as a Service-Database (Add New Item > Data > Service-Database).
The code for the button is (output follows below it):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(Properties.Settings.Default.Database1ConnectionString);
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
thisConnection.Open();
nonqueryCommand.CommandText = "CREATE TABLE MyTable1 (intColumn int)";
Console.WriteLine(nonqueryCommand.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());
nonqueryCommand.CommandText = "INSERT INTO MyTable1 VALUES (99)";
Console.WriteLine(nonqueryCommand.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}",
nonqueryCommand.ExecuteNonQuery());
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close(); // close connection
Console.WriteLine("Connection Closed.");
}
}
OUTPUT:
CREATE TABLE MyTable1 (intColumn int)
Number of Rows Affected is: -1
INSERT INTO MyTable1 VALUES (99)
Number of Rows Affected is: 1
Connection Closed.
Nothing Shows up on Server Explorer Though No additional Tables even if I close it down and reconnect.
If i push the button to make it issue the same again i get:
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyTable1' in the database.
but still nothing on server explorer.
The exception told you exactly what's going on. Your table already exists. You can't create it again. You need to DROP the table if it already exists.
Nothing Shows up on Server Explorer Though No additional Tables even if I close it down and reconnect.
Whenever you execute your program, Visual Studio's project management automatically deploy (copy that database) .mdf database file at deployment folder Debug\Bin. I think your code uses a database which is located at Debug\Bin folder (which will be not shown in server explorer) and Server Explorer shows a database (.mdf) which is located at root of project folder and it is empty.
Try spceifying the commandType property of the SqlCommand = CommandType.Text
Also make sure that you are connecting to the same instance of SQL. You can get your code's by breakpointing the line after you open the connection (for it's when you know it works) and going looking for the servername.
Note that you can have multiple SQL instances in one machine... so you could be working on the right server (say localhost) and yet not be accessing the correct instance (say SQLEXPRESS instead of MSSQLSERVER).

Categories

Resources