Why is the inserted value only visible while the program is running? - c#

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?

Related

Why won't my query execute in my code, while it executes just fine in normal sql?

I've run into a problem while making a project for school, we are supposed to import data from a .txt file to our C# database. I thought I had it figured out but my "insert" lines weren't inserting data to my tables. So, in the end, I tried to insert only 1 line with all values written in, and it still won't insert the data into the database.
I tried the "New query" option by right clicking on my table and copy-pasted the insert line from my code, and that worked just fine, so I don't know why the line in the code isn't working.
class Program
{
static void Main(string[] args)
{
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
string q;
dataConnection.Open();
q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
SqlCommand dataCommand = new SqlCommand(q, dataConnection);
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
dataConnection.Close();
}
catch { Console.WriteLine("Fail"); }
}
}
I tried pasting the executenonquery line in a try block, and it DOES write "Success" on my screen, but the insert line does NOT execute.
Check the return value of dataCommand.ExecuteNonQuery(); (integer Value) if it return -1 something went wrong (for example a transaction rollback). If 0 no rows were affected.
int return_value = dataCommand.ExecuteNonQuery();
if(return_value > 0)
//goood :)
else
//something wrong :(
EDIT:
Btw is better dispose the commands after using them like below:
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
dataConnection.Open();
string q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
using(SqlCommand dataCommand = new SqlCommand(q, dataConnection))
{
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
}
catch { Console.WriteLine("Fail"); }
}
dataConnection.Close();
EDIT2: Considering questions in the comments.
What are you saying writing |DataDirectory| is "search in the application path for that dasabase", if you're debugging your application it means that it search the dabase in the output debug folder... If you wont that you should target a database out of your appliation directory with a relative/absolute path (look AppDomain.SetData method) or copy your database in your application directory... is hard answer you without knowing your goal :)
To be more specific, before initialize your SqlConnection call the following code:
AppDomain.SetData("DataDirectory", "C:\\TEST\\");
To set your |DataDirectory| pointing at your database path.

c# update database isn't working

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

C# Reusable Mysql Class

I am having some issues with a class that I have created to perform different database commands.
1st) The program is local ran, and will only run locally. It will only ever connect to the database on the localhost.
Therefore I have a simple class setup, called databaseConnector that allows me to pass a string to it with the required Mysql query to perform the different functions.
For instance.
I use:
var db = new databaseConnector();
db.Update("UPDATE * WHERE.....");
However, it seems if I ever want to use a different query, or another query, it's not working and throwing errors.
For instance.
var db = new databaseConnector();
db.Update("UPDATE * WHERE...");
db.INSERT("INSERT INTO * WHERE.....");
Will give me an error on the insert execution. Any ideas why? I have resorted to creating it again. So I have to redo:
db = new databaseConnector();
to then use the Insert command.
Here is an example of my insert function.
public void Insert(string query)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
Now that I think about it. Should I call my db.openConnection() before doing it. Since when I initialize it in the first var db = new databaseConnection(), it's opening? And then in each function it's closing it, but only checking if it's open, instead of attempting to open, doing query, then closing.

How to call multiple stored procedures in a MySql database

I am able to get this program to work with one stored procedure. Is it possible to call multiple stored procedures from MYSQL in C#? If so what is the most efficient way of doing so? Here is a snippet of my code to show what I've done thus far:
public static string RunSQL()
{
// Here is where it is connecting to local host.
string connStr = "server=localhost;user=xxxx;"
+ "database=xxxx;port=3306;password=xxx;"
+ "Allow User Variables=True";
MySqlConnection conn = new MySqlConnection(connStr);
// Here is where the connection gets opened.
conn.Open();
// Here I call the CN_renumber stored procedure.
MySqlCommand CN_renumber = new MySqlCommand("CN_renumber", conn);
CN_renumber.CommandType = System.Data.CommandType.StoredProcedure;
object result = CN_renumber.ExecuteNonQuery();
// Disconnect from local host.
conn.Close();
return result.ToString();
}
You can reuse your object of MySQLCommand multiple times, but before that you should make sure you call myCommand.Parameters.Clear();, then assign the new Stored Procedure name again.
Useful question with example here

C# - ExecuteNonQuery() isn't working with SQL Server CE

I got some data inputed by the user that should be added to a Database File (.sdf). I've choose Sql Server CE because this application is quite small, and i didn't saw need to work with a service based database.
Well any way.
Here goes the code:
public class SqlActions
{
string conStr = String.Format("Data Source = " + new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\basedados.sdf");
public SqlCeConnection SQLCEConnect()
{
SqlCeConnection Connection = new SqlCeConnection(conStr);
Connection.Open();
return Connection;
}
public Boolean AdicionarAuditorio(string Nome, int Capacidade)
{
string Query = "INSERT INTO auditorios (nome, capacidade) VALUES (#Nome, #Capacidade)";
using (var SQLCmd = new SqlCeCommand(Query, SQLCEConnect()))
{
SQLCmd.Parameters.AddWithValue("#Nome", Nome);
SQLCmd.Parameters.AddWithValue("#Capacidade", Capacidade);
if (SQLCmd.ExecuteNonQuery() == 1)
{
return true;
} else {
return false;
}
}
}
}
I use the AdicionarAuditorio(string Nome, int Capacidade) function to Insert the data. running ExecuteNonQuery() which is supposed to return the number of affected rows after he as run the query.
So it should return 1 if the query as successful, right?
In the end he returns 1, but if I browser the table data, the data that the query should add isn't there.
So whats wrong here?
NOTE. If your thinking that the
problem is the connection: I can't see
why is the problem once i got some
Select statements that use that
connection function SQLCEConnect()
and they all work pretty well.
Thanks in advance.
Are you sure you are looking at the right file? When you build your app in VS, it copies the SDF file as content to the target folder, so the database in your project will not reflect any updates. Your code is picking up the the file location there.
This is btw not a good practice, because once deployed, the program folders are not writable to your app (could this be the problem - did you already deploy?). Instead, the database file should reside in your appdata folder.
Is it possible that you make the call to AdicionarAuditorio in a TransactionScope without calling transactionScope.Complete()?

Categories

Resources