c# update database isn't working - c#

So I've searched the net to find a solution and what I found is that when we execute F5 in visual studio, it actually copies the original database into a new one and it uses the copy in the code so the changes you'd have made wouldn't be there and they told me to set the database properties to "Copy if newer" and it isn't working, I don't get any error messages but the original is not being updated.
I made a test to see if this code was updating at least the copy and it is...
After running my application when I see the database the changes aren't there
So I want to update the original database how do I do that?
private void button3_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["NembManagement.Properties.Settings.NembDatabaseConnectionString"].ConnectionString;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("UPDATE Alunos SET Nome = #a WHERE Id=1", connection))
{
DataTable AlunosInfo = new DataTable();
connection.Open();
command.Prepare();
command.Parameters.Clear();
command.Parameters.AddWithValue("#a","aff");
command.ExecuteNonQuery();
//test to see if it was updating the copy and it is
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Alunos WHERE Alunos.Id=1 ", connection);
adapter.Fill(AlunosInfo);
}
}

I found the solution somehow, i changed my database property Copy to nevercopy and i got another error saying that connection could not be opened so i solved this one by correcting the connection string in the app config

Related

Why is the inserted value only visible while the program is running?

my problem is currently that I add a player to the database and that player is visible only as long as the program runs.
The test() method should add a player to the database.
private static void Test()
{
SqlConnection connection;
string connectionString = ConfigurationManager.ConnectionStrings["Footbal.Properties.Settings.cn"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();
string query = "INSERT INTO Players(id, player_name, player_price, player_rating) VALUES(#id, #player_name, #player_price, #player_rating)";
string name = "Ronaldo";
SqlCommand testInsert = new SqlCommand(query, connection);
testInsert.Parameters.AddWithValue("#id", 43);
testInsert.Parameters.AddWithValue("#player_name", name);
testInsert.Parameters.AddWithValue("#player_price", 34);
testInsert.Parameters.AddWithValue("#player_rating", 54);
testInsert.ExecuteScalar();
connection.Close();
}
After this method the DataGridView is filled. (playersTableAdapter acts as a bridge between DataSet(db_PlayersDataSet.Players) and database)
playersTableAdapter.Fill(db_PlayersDataSet.Players);
So far everything works as expected. And now when I close the program, the added data is gone.
What is the problem?
I suspect you're using an attached-when-the-program-runs database, meaning that when the project is run a new database (copied from the project folder) is output and attached
Attach your db permanently and adjust your connstr, or just accept the behavior; it'll be fine when the app is deployed
In your test() method, you need to use ExecuteNonQuery() instead of ExecuteScalar(). Just change below line in above code and it should work.
Change
testInsert.ExecuteScalar();
to
testInsert.ExecuteNonQuery();
Is "Id" Primary Key in the database?
Did you try to insert without "Id", or to use different "Id" for new player?

MySQL SET PASSWORD executing fine with 0 rows affected but not taking effect?

I have a C# app where if you click a button it will take whatever the password text box has and attempt to set the MySQL database with that user in usernameLabel.Text. However, this executes fine but I can still refresh the database in PHPMyAdmin and it works fine with the old password. The new password gives an access denied so it clearly hasn't changed the password even though there were no errors. Does anyone have an idea on why this might be the case?
This is the code for the button.
private void submitNewMySQLPasswordButton_Click(object sender, EventArgs e)
{
var connection = ConfigurationManager.ConnectionStrings["system"].ConnectionString;
MySqlConnection myconn = new MySqlConnection(connection);
myconn.Open();
MySqlCommand command = myconn.CreateCommand();
command.CommandText = "UPDATE mysql.user SET Password=PASSWORD('#NewPassHere') WHERE User='#User';";
command.Parameters.AddWithValue("#User", usernameLabel.Text);
//command.Parameters.AddWithValue("?hostname", "%");
command.Parameters.AddWithValue("#NewPassHere", newPasswordTextBox.Text);
int rows = command.ExecuteNonQuery();
myconn.Close();
}
You need to remove the quotes around the parameters, otherwise it's just an ordinary string.
command.CommandText = "UPDATE mysql.user SET Password=PASSWORD(#NewPassHere) WHERE User=#User;";
command.Parameters.Add("#User", SqlDbType.VarChar).Value=usernameLabel.Text;
command.Parameters.Add("#NewPassHere", SqlDbType.VarChar).Value=newPasswordTextBox.Text);
int rows = command.ExecuteNonQuery();

Open MSQL procedure from C# application (using System.Diagnostics)

I am having difficulties in finding a solution for opening a stored procedure straight to MSQL management studio for modifying in a new SQLQuery from my C# application (winform).
Here is my code:
Process openSQL = new Process();
openSQL.StartInfo.FileName = "Ssms.exe";
openSQL.StartInfo.Arguments = "dbo.getResults"; //name of the stored procedure I want to open
openSQL.Start();
I am getting error after executing the code :"The following files were specified on the command line: dbo.getResults These files could not be found and will not be loaded."
How am I supposed to "point" to the stored procedure in C# and get its definition displayed and ready to get modifications in MSQL management studio?
This isn't possible I'm afraid. If you run ssms -? from the command line you can see all the parameters that you can pass in:
Some options:
Let users edit procs themselves. After all, anyone capable of doing this will understand how to use SSMS properly.
Make your own UI. You can read the contents of a stored procedure and display them in a text box. The downside is that you lose features such as syntax highlighting (unless you also build that in too)
You could download the procedure and store it in a procedure.sql file and get SSMS to open that. Don't forget to pass in the server, database and credentials.
I found a way to open a stored procedure script straight to MSQL management studio for modifying in a new SQLQuery from my C# application (winform).
I am taking the script of the procedure with EXEC sp_helptext 'procedure_name'
The result set is filled in a DataSet
And the DataSet is getting written in an empty .sql file
The .sql file is getting opened in MSQL Managment Studio with System.Diagnostics;
Here are the steps with code snippets:
private void saveProcToAFile()
{
StreamWriter log;
if (!File.Exists("procedureToBeLoaded.sql"))
{
log = new StreamWriter("procedureToBeLoaded.sql");
}
else
{
log = new StreamWriter(File.Create("procedureToBeLoaded.sql"));
}
SqlConnection conn = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = string.Format("EXEC sp_helptext '{0}'", "procedure_name"); //Step 1.
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds); //Step 2.
conn.Close();
foreach (DataRow dr in ds.Tables[0].Rows)
{
log.WriteLine(dr[0]); //Step 3.
}
log.Close();
}
Step 4.
private void contextMenuStripOpenInSqlStudio_Click(object sender, EventArgs e)
{
saveProcToAFile();
Process openSQL = new Process();
openSQL.StartInfo.FileName = "Ssms.exe";
openSQL.StartInfo.Arguments = "procedureToBeLoaded.sql";
openSQL.Start();
}

update database using SqlDataAdapter in C#

I have below code to update my database table when button is clicked but it doesn't work.
protected void Button_Click(object sender, EventArgs e)
{
HasinReservation.Entities.Db.Transaction dt = new Transaction();
SqlConnection connection = new SqlConnection(
#"Data Source=192.x.x.x\Sql2008;Initial Catalog=GardeshgariKish;User ID=cms;Password=xxxxx;MultipleActiveResultSets=True;Application Name=EntityFramework");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(
"Update Transaction SET IsCancelled = 1 WHERE BarCodeNumber = #Value1", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
string barcode = dgvData.Rows[0].Cells[12].Text;
sqlCmd.Parameters.AddWithValue("Value1", barcode);
connection.Close();
}
I am troubled by your implementation of Entity Framework but then not using the framework for what it was designed...
You have configured your data adapter and the command, and even opened the connection... but you have not actually executed the command.
sqlCmd.ExecuteNonQuery();
I understand that your actual business logic may have been replaced with this simple CRUD operation, but the main reason that we use the Entity Framework is to avoid writing any T-SQL in our business logic. Why didn't you use the framework to commit the change:
protected void Button3_Click(object sender, EventArgs e)
{
// cancel the selected transaction
string selectedBarcode = dgvData.Rows[0].Cells[12].Text;
using(var dataContext = new HasinReservation.Entities.Db())
{
var transaction = dataContext.Transaction.Single(t => t.Barcode == selectedBarcode);
transaction.IsCancelled = true;
dataContext.SaveChanges();
}
}
This in itself may not be a great solution but it uses the framework to do exactly what you attempted to do manually.
Why are you trying to use a SqlDataAdapter to execute an UPDATE statement? When constructing a SqlDataAdapter with a SqlCommand object, that command object represents the SELECT command for the adapter. An UPDATE statement doesn't select anything, and a SELECT command doesn't update anything.
Get rid of the SqlDataAdapter entirely and just execute the command:
sqlCmd.ExecuteNonQuery();
You'll probably also want to add some error handling so exceptions don't reach the UI (and to ensure the connection is properly closed on error conditions). You also don't seem to be doing anything with that Transaction object, so you can probably get rid of that too.

Getting Error while connecting to DB using c#

Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.

Categories

Resources