Updating Database through c# code [duplicate] - c#

This question already has answers here:
Why saving changes to a database fails?
(2 answers)
Closed 5 years ago.
:)
I've started with project of creating some program for Library. I mean, it is a simple program which has login form and some features for admin. Also, I've done database (everything is done with Visual Studio 2013), SQL Service-based Database. I followed some Youtube tutorials and now when I added button for adding users in database I run into "problem". This is code for Add button:
private void btnAdd_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.KnjiznicaDBConnectionString"].ConnectionString;
string query = "INSERT INTO User VALUES(#Name,#Surname,#Year,#Mail)";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
{
connection.Open();
command.Parameters.AddWithValue("#Name", txtName.Text.Trim());
command.Parameters.AddWithValue("#Surname", txtSurname.Text.Trim());
command.Parameters.AddWithValue("#Year", txtYear.Text.Trim());
command.Parameters.AddWithValue("#Mail", txtMail.Text.Trim());
command.ExecuteScalar();
}
}
Now, I know that user is added into database, because I can see it in DataGridView which is also in Form, but when I check directly in Database (I mean in Server Explorer->Database_name->Tables->User (Show Table Data)), that new user is actually not added there. And no matter if I exit Visual Studio, as long as I don't shut down computer, that new User will be in DataGridView but not in "Database". And when I restart computer and start Visual Studio again, new user won't be even in DataGridView. Only permanent users are those that I add directly through Show Table Data or with New Query also in Server Explorer.
I would like to know what should I correct so all users added through the code and Form are implemented in "real Database" not just DataGridView.
Thanks :)

Wrong command
You need SqlCommand.ExecuteNonQuery
And you would be wrapping open and command in Using blocks

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.

Get specific column of specific user in datatable

I have a data table, in the data table, I have 3 columns: USERNAME, PASSWORD, and Money.
I want to make a specific setting in my program to make a label the amount of money the user has, and for each user, it will show something else depending on who is logged on at the moment, is it possible and if yes how can I do it?
Thanks in advance.
You can put the amount of money in your label by writing some code. This is used for MSSQL Database connections(in your case).
Here is an example:
using System.Data.SqlClient;//Add this in the using statements at the top of your code.
using (SqlConnection conn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename =" +Application.StartupPath+ #"\Database1.mdf; Integrated Security = True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Money FROM Users WHERE Username = #username";
cmd.Parameters.AddWithValue("#username", "User1");
var reader = cmd.ExecuteReader();
reader.Read();
label1.Text = reader.GetValue(0).ToString(); //reader returns an object, you have to convert it in your type.
//GetValue(selected column number)
}
conn.Close();//This line is optional. The connection closes automatically when the using() statement ends.
}
You can add this code in your Form Load event.(If you are working with Win Forms).
The second method is to use Dataset with binding the label to it. This is also powerful and you do not need to know too much sql or how to code, it is more complicated at the beginning but it`s easier and saves time. You can apply it to any of your form elements(buttons, datagridviews,combobox,textbox,etc).
First, go to your label properties and find "DataBindings". Click on advanced. Just click next until you see the connect to database option. If your are connected already with visual studio to your database it will appear in that combobox, otherwise click new connection(I suppose you worked in service based database).Click next and finish. After you have to bind the label to the database(it will create a generated code in your Form Load Event). If you have only one record(one user) in the table it will show only one value, but if you want to show a specific user, you can change that "Fill" generated method in your Form Load Event in other(filtered one with WHERE SQL Clause). You can change that fill method in the Dataset Added in the bottom of your designer of the form. Click on that little arrow near it and choose "edit in designer" option. Click on the table adapter section and right click on his function(in this case Fill() method) and click configure. Here you can change the sql statement and put a WHERE clause in the end.(ex Where Username = ?) The "?" means some variable. After pass in the function created in the form load event your user`s username next to that dataset thing. Done. If you want to work with Win Forms and sql databases I advise you to learn how to use The Datasets, Bindings and TableAdapters. Hope it helps.
Screenshots of my explanations:
!!!! [UPDATE] !!!!
Here is my example program on google drive: Link.
On the right side you can open my service based database(in the project files(Database1)).I'll attach some useful screenshots for creating addition functions in a dataset's table adaper. Also, you have the second method commented in the Form1 load event.

"C:\USERS\ME\DATABASE.MDF" requested by the login. The login failed. Login failed for user 'me-PC\me'

Basically every time I run my game MS SQL database crashes and returns this error message.
Cannot open database "C:\USERS\ME\SOURCE\REPOS\A GIRL CALLED LORRY\A GIRL CALLED LORRY\DATABASE.MDF" requested by the login. The login failed.
Login failed for user 'me-PC\me'.
I did not change any of the SQL or C# code in my project to cause this error. All I did was simply modify a table within my database by adding a new column of type string.
I've tried using SMSS to open my DataBase.mdf file within my project to see if my user has privileges to access it, however I was unable to open my DataBase.mdf file because it wouldn't even show up within SMSS. So I'm not sure how I can get privileges to access my database again. I also tried removing all the changes I've added to the DB which caused the error in the first place however the error still persists.
As I've said, the error was caused by modifying a table within my database, but there is a small piece of code where the game crashes as soon as I attempt to open the database to remove data:
//this method is used to initialize the database.
public static void createSave() {
//database stuff:
con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\me\\source\\repos\\A Girl Called Lorry\\A Girl Called Lorry\\Database.mdf;Integrated Security=True");
adp = new SqlDataAdapter();
ds = new DataSet();
Console.WriteLine("we are in!");
//the below code only initializes if isNewGame is set to true.
removeAllFromInventory();
rewriteCurrentObjects();
loadDefaultNpcs();
}
//removeAllFromInventory is where it crashes.
//removes all items from inventory:
public static void removeAllFromInventory() { //this only applies if
//isNewGame is set to true since we want to wipe the inventory in a new game
if (!isNewGame) return;
con.Open(); //here is where it crashes.
adp.SelectCommand = new SqlCommand("DELETE FROM curInventoryItems", con);
adp.SelectCommand.ExecuteNonQuery();
con.Close();
}
However I was unable to open my DataBase.mdf file because it wouldn't even show up within SMSS. So I'm not sure how I can get privileges to access my database again. I also tried removing all the changes I've added to the DB which caused the error in the first place however the error still persists.
There is confusing part in your question, when you unable to connect .MDF how could you remove changes that was added into DB.
However, following steps might be helpful to get your database back to normal:
Verify the account (me-PC\me) has permissions on C:\USERS\ME\SOURCE\REPOS\A GIRL CALLED LORRY\A GIRL CALLED LORRY\DATABASE.MDF
If doesn't work after the permissions, you can troubleshoot the SQL Localdb connections using these steps
Install SQL Express (as it's difficult to manage with LocalDB database engine), and attach Database.mdf into SQL Express engine. You can do this using following command via SSMS
Once your database ready at SQL Express, you can change your connection string to "Data Source=Localhost\\SQLEXPRESS;Initial Catalog=YourNewDBName;Integrated Security=True"
In case issue even with SQL Express, you may follow these steps..
--- You need to move "Database.mdf" and ".ldf" files into "C"\SQLData" folder before executing the command
CREATE DATABASE YourDatabase
ON (FILENAME = 'C:\SQLData\Database.mdf'),
(FILENAME = 'C:\SQLData\Database_log.ldf')
FOR ATTACH;

How do I run a SQL Server job programatically in C#? [duplicate]

This question already has answers here:
How to invoke the job in SQL Server agent from windows application
(6 answers)
Closed 6 years ago.
Inside SQL Server Management Studio there are more than just databases listed in the Object Explorer. Under SQL Server Agent, we have "Jobs". One of these jobs that we have updates the client to match the cache. This is important because of how our cache system works. If we make a change to the database, it is not reflected if we run this job.
So, in the C# code, there are times when I make a change to a database table that I need to run this job afterwards. It is easy to do in SQL Server Management Studio. I just right click on the job and click on "Start Job at Step..." but how would I do the same thing in C#?
The problem I have been having is not answered in what might be a duplicate post. The command line is "execute msdb.dbo.sp_start_job #job_name='Update Client Matching Cache'" and, while I have permissions to run this command from the SQL line (thus showing I have permissions), I cannot run it from the code. Passing the job name, "update client matching cache" to this procedure fails to run:
public static void RunStoredProcedure(string strSQLJob)
{
SqlCommand ExecJob = new SqlCommand();
ExecJob.CommandType = CommandType.StoredProcedure;
ExecJob.CommandText = "msdb.dbo.sp_start_job";
ExecJob.Parameters.AddWithValue("#job_name", strSQLJob);
using (SqlConnection sc = DatabaseManager.SqlConnection())
{
sc.Open();
using (ExecJob)
{
ExecJob.Connection = sc;
ExecJob.ExecuteNonQuery();
}
}
}
The error is: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The EXECUTE permission was denied on the object 'sp_start_job', database 'msdb', schema 'dbo'.
I also get the same error if I open Visual Studio in admin mode.
You need to use Microsoft.SqlServer.Management.Smo.Agent namespace..In this namespace you have job class which has INVOKEmethod.Here is some sample code from MSDN..
Server srv = new Server("(local)");
Job jb = new Job(srv.JobServer, "Test Job");
jb.Create();
JobStep jbstp = new JobStep(jb, "Test Job Step");
jbstp.OnSuccessAction = StepCompletionAction.QuitWithSuccess;
jbstp.OnFailAction = StepCompletionAction.QuitWithFailure;
jbstp.Create();
jb.ApplyToTargetServer(srv);
jb.IsEnabled = true;
jb.Invoke();
You can create a new job and a new "Task" table.
The new job would be checking the status of the "Task" table every 5 minutes or so. If there is a new row in that table with a status, for example: "pending", then, this job will start the target job, and will change the status to "in progress".
Finally, the last job can include a step to change the status again to "success" or "failure" when it's finished.
Using the answer in a similar question almost works apart from a privilege error being thrown How to invoke the job in SQL Server agent from windows application

Connecting a MS Access (.mdb) Database to a MVC3 Web Application

Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

Categories

Resources