Store a timer value in a database? c# - c#

I have a global variable which is set up for the timer, "I", the program I'm creating has a user play a game level and store their level time in a database with other users. This is what I have already.
public static class Global
{
public static int I = 0;
}
^ this is the global variable for the timer.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
}
else // else it will display this error
{
MessageBox.Show("Please enter the correct login details");
}
^^ this is the code for the end screen of the game, as you can see i've tried taking the Global.I and addwithvalue #Score which is in the HighScore table in my database.
Now when i click the button it doesn't write anything to the database but I don't get any errors when i try and save, this is why i'm confused.
Any help would be appreciated, Thanks.

before executing any command you first must open the connection. You are opening the connection after calling Fill()!!. You will also have to execute cmd. Try:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
cmd.ExecuteNonQuery();
It is also admirable that you know how to correctly use parameters, however you use them only in 1 case instead of both queries.

Related

The code is running but UPDATE command does not update data in the table

I have to write the code which update a user's password. There must be entered a user's username (Brugernavn) , password (Adgangskode), new password and confirm password. The code is running, but UPDATE command does not update the password.
Until now, I have tried with this code (I know, that parametrized query should be used, but I don't have any idea about how to write such query, while this is combination of a SELECT and UPDATE statements):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Login_data WHERE Brugernavn='" + textBox1.Text + "' AND Adgangskode='" + textBox2.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ErrorProvider errorProvider1 = new ErrorProvider();
errorProvider1.Clear();
if(dt.Rows[0][0].ToString() == "1")
{
if(textBox3.Text == textBox4.Text)
{
SqlDataAdapter sda1 = new SqlDataAdapter("UPDATE dbo.Login_data SET Adgangskode='" + textBox3.Text + "' WHERE Brugernavn='" + textBox1.Text + "' AND Adgangskode='" + textBox2.Text + "'", con);
MessageBox.Show("Adgangskoden er skiftet.", "Bekræftelse", MessageBoxButtons.OK);
}
else
{
errorProvider1.SetError(textBox3, "Adgangskode passer ikke");
errorProvider1.SetError(textBox4, "Adgangskode passer ikke");
}
}
else
{
errorProvider1.SetError(textBox1, "Du har tastet forkert brugernavn");
errorProvider1.SetError(textBox2, "Du har tastet forkert adgangskode");
}
}
The expected result is that password will be updated.
Instead of using a SqlAdapter for your update statement, create a new SqlCommand as you do for the Select statement. Then call the ExecuteNonQuery method on the SqlCommand object.

C# SQL Update Current Insert Method Parameters.AddWithValue

I wrote an SQL insert method in C # and would like to convert it, so that the rubrics (username, victories, defeats) can be changed with # and Parameters.AddWithValue. How can I solve this problem
SqlConnection con = new SqlConnection(#"Data Source=******;Initial Catalog=UserDB;Integrated Security=True");
SqlCommand cmdinsert = new SqlCommand("Insert UserTabelle values('" + 0 + "','" + 0 + "','" + txtBenutzerName.Text + "')", con);
con.Open();
cmdinsert.CommandType = CommandType.Text;
cmdinsert.ExecuteNonQuery();
con.Close();
MessageBox.Show("Account erfolgreich erstellt");
Login login = new Login(txtBenutzerName.Text);
login.Show();
this.Close();
Use the following code as an example.
using (var connection =
new SqlConnection(
#"Data Source=******;Initial Catalog=UserDB;Integrated Security=True"))
{
connection.Open();
using (var command =
new SqlCommand(
#"
insert into UserTabelle([Name], [Other])
values (#name, #other)",
connection)){
command.Parameters.AddWithValue("#name", txtBenutzerName.Text);
command.Parameters.AddWithValue("#other", "some value");
command.ExecuteNonQuery();
}
connection.Close();
}

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

Database System.Data.SqlClient.SqlException

I'm trying to use database:
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DB\LogiDB.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select * from tbl_Login Where username = '" + textBox1.Text.Trim().ToLower() + "' and password = '" + textBox1.Text.Trim().ToLower() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
//
}
my files is:
dbo.Table.sql
LogiDB.mdf
LogiDB_log.ldf
tbl_Login.sql
not sure what I'm doing wrong but when I press to button I got this with line sda.Fill(dtbl);:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'tbl_Login'.
As the error says: Invalid object name 'tbl_Login'
This might mean:
tbl_Login table doesn't exist in you database
you are connecting to wrong database
Since you have tbl_Login.sql script, I guess it contains table definition. Therefore you would need to run script to create table in your LogiDB database.
Here there is example how to connect to local database
Here is my code work perfectly,
You can try this and compare your code
SqlConnection cn = new SqlConnection("Data Source=AVREST\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("select loginID,loginPassword from logintavle where loginID='" + textBox1.Text + "'and loginPassword='" + textBox2.Text + "'", cn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
if (dataset.Rows.Count > 0)

C# Login page. SQL Server " sda.Fill(dt); " ERROR

I was watching this video. It basically teaches me how to create my own login page using SQL Server.
So after following exactly what he did, when I click the submit button I have an error highlighting sda.Fill(dt);. I am pretty new to SQL Server, please advise!
My code:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Glenntdy\Documents\GlennTeoDB.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Table where Username='"+txtName.Text + "' and Password = '" +txtPassword.Text + "'",con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Please double check your Username and password");
}
Picture of error:
Table is a reserved keyword and should be surrounded by braces like [Table]. Additionally it is not recommended to construct your query the way you do, because of SqlInjection. Read more on SqlParameters. One more thing.. you should close the SqlConnection after use.
enter image description here
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection (#"Data SOURCE=.\SQLEXPRESS;AttachDbFilename=C:\Users\itmaint\source\repos\database\database\G-data.mdf;Integrated Se[a.][2]curity=True;Connection Timeout=30;User Instance=True");
string query ="Select * From Login Where Username='" + textBox1.Text.Trim() + "' and Password ='" + textBox2.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
Form2 ss = new Form2();
this.Hide();
ss.Show();
}

Categories

Resources