I am running into problems with my Database not opening because it is already, apparently, open.
Unable to copy file "j:...\KAELC_DB.mdf" to "bin\Debug\KAELC_DB.mdf".
The process cannot access the file 'j:...\KAELC_DB.mdf' because it is
being used by another process.
Unable to copy file "j:...\KAELC_DB_log.ldf" to
"bin\Debug\KAELC_DB_log.ldf". The process cannot access the file
'j:...\KAELC_DB_log.ldf' because it is being used by another process.
I found a reply to an old question on StackExchange, linked to here https://stackoverflow.com/a/3998383, by "Justin", which looks to resolve that problem (and I have also read in other places that "using" is one of the most efficient ways of programming in C#) but how do I use this in my code ?
I have created a small Project that does nothing but allow me to press a button in order to process a SQL statement, but I'm confused as to what "Justin" means by "Use the connection" ... how do I put SQL statements into this code ?!?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MySqlTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Open SQL File
using (SqlConnection conn = SqlHelper.GetConn())
{
// Use the connection <<< How ?!?!?
}
}
private void button2_Click(object sender, EventArgs e)
{
//Insert Record Into SQL File
}
private void button3_Click(object sender, EventArgs e)
{
//Read Record From SQL File
}
private void button4_Click(object sender, EventArgs e)
{
//Read All Records From SQL File
}
private void button5_Click(object sender, EventArgs e)
{
//Delete Record From DQL File
}
private void button6_Click(object sender, EventArgs e)
{
//Close SQL File
}
private void button7_Click(object sender, EventArgs e)
{
//Quit
this.Close();
}
class SqlHelper
{
public static SqlConnection GetConn()
{
SqlConnection returnValue = new SqlConnection(#"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\SqlTestDB.mdf;Initial Catalog=MySqlDB;Integrated Security=True");
returnValue.Open();
return returnValue;
}
}
}
}
if all you want to do is run an SQL command, use an SQLCommand object. (MSDN docs here)
here is the sample code from the article...
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
things to note:
uses a SqlConnection object with a Using block
uses an SqlCommand object
uses an SqlDataReader object
explicitly closes the SqlConnection with finished with it
Related
I'm trying to get the data in my "Jokes" table to update in SQL Server when I change the cell(s) in this DataGridView and click the "Update" button I made. I tried following along with a tutorial, but it seems to just not work. What do I need to change here to make it work? I'm not getting any errors oddly, so it must just be the way I did it or something. Thanks for any help.
This is the entire code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TestProject1
{
public partial class UserControl3 : UserControl
{
SqlConnection con = new SqlConnection(#"Data Source=MSI;Initial Catalog=Jokes;Integrated Security=True;");
SqlDataAdapter adpt;
DataTable dt;
DataSet ds;
SqlCommandBuilder cmdbl;
public UserControl3()
{
InitializeComponent();
ShowData();
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.jokesTableAdapter.FillBy(this.jokesDataSet.Jokes);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void UserControl3_Load(object sender, EventArgs e)
{
con.Open();
ds = new DataSet();
adpt.Fill(ds, "Jokes");
}
public void ShowData()
{
adpt = new SqlDataAdapter("SELECT * FROM Jokes", con);
dt = new DataTable();
adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
private void BackGridButton_Click(object sender, EventArgs e)
{
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
cmdbl = new SqlCommandBuilder(adpt);
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Double check (by debugging) whether the property builder.GetUpdateCommand().CommandText is returning a valid update command.
If not, add the update your try-block in button1_Click to look like this
cmdbl = new SqlCommandBuilder(adpt);
adpt.UpdateCommand = cmdbl.GetUpdateCommand();
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");
I do admit that the second in line above code snippet should not be required theoretically looking at the way you instantiated the SqlCommandbuilder. But it would just be to re-affirm and also part of the reason why I suggested to check that property in Debug mode.
I am trying to make my own login screen and registration and I got to the part where I want to know if the user exists. For some reason I create my user in my database and it keeps saying "no" when my user already exists.
I don't see what the problem is because I followed this youtube video and I understand the code so I really don't know why it doesn't work. I think my database is not connected because I am using a different port on xamp and I tried typing localhost:3306 but that didn't work, I get an error, so I tried localhost but now I think it's not connected
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Krunsj_V1
{
public partial class Officiallogin : Form
{
public Officiallogin()
{
InitializeComponent();
}
public Officiallogin(bool doNotMakeInvisibile)
{
InitializeComponent();
}
private void bunifuCustomLabel1_Click(object sender, EventArgs e)
{
this.Hide();
Register Register = new Register();
Register.ShowDialog();
}
private void btnLogin_Click(object sender, EventArgs e)
{
DB db = new DB();
String username = txtUsername.Text;
String password = txtPassword.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = #usn and 'password' = #pass", db.GetConnection());
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = username;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = password;
adapter.SelectCommand = command;
adapter.Fill(table);
// check if there user exists or not
if (table.Rows.Count > 0)
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}
//Application.Exit();
//Mainwindow main = new Mainwindow(true);
//main.Visibility = System.Windows.Visibility.Visible;
//main.ShowDialog();
}
private void txtPassword_OnValueChanged(object sender, EventArgs e)
{
//txtPassword.isPassword = true;
}
//////////////////////////////
// close button properties //
//////////////////////////////
private void lblclose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void lblclose_MouseEnter(object sender, EventArgs e)
{
lblclose.ForeColor = Color.Black;
}
private void lblclose_MouseLeave(object sender, EventArgs e)
{
lblclose.ForeColor = Color.Purple;
}
}
}
The problem is in this SQL statement:
WHERE `username` = #usn and 'password' = #pass
'password' is a string literal, so you are asking if the user's parameterized password is the literal string "password".
To quote a column name in MySQL, use backticks:
WHERE `username` = #usn and `password` = #pass
Or drop them entirely, since username and password aren't reserved words in MySQL:
WHERE username = #usn and password = #pass
Finally, this code implies that you're storing the users' plain text passwords directly in the database. This is a huge security vulnerability and should never be done. Research password hashing (e.g., at https://auth0.com/blog/hashing-passwords-one-way-road-to-security/) or use an off-the-shelf login system instead of trying to build your own.
I've tried every single solution ive found on here and still cant get it to work
Currently all i get is a blank combo box regardless of what i change, can anyone see where im going wrong for title? (Yet to try price due to success with my titles combo box)
I'm trying to pull Title and Price out of my Game_Details table in the Aliena_Store MySQL database.
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace Aliena_Store
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void Game_List_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection
"server=localhost;user=root;database=Aliena_Store
;port=3306;password=Blackie");
string selectQuery = "SELECT Title,Price FROM
Aliena_Store.Game_Details";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
Game_List.Items.Insert(i, reader.GetString("Title"));
i++;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Game_Quantity_TextChanged(object sender, EventArgs e)
{
}
private void Game_Price_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Your SQL may not be returning what you think
"Select Title * ...." you probably didnt want that "*" in there. Are you getting a number of blank entries or just no entries?
You do know your code is only running if you could change items on the drop down right?
If your dropdownlist is Game_List, then you should try :
int i =0
while (reader.Read())
{
Game_List.Items.Insert(i, reader.GetString("Title"));
i++
}
I am trying to connect a MySQL database to a winform using C#. I am receiving this error: System.ArgumentException: 'Keyword not supported: 'host'. I have already checked that the database has a proper connection using the test connection and the connection string that I am using is the one provided to me using the server explorer. After doing research, the issue lies in either the references I'm using or in the app.config itself. Does anyone have any experience with this issue or can offer any feedback? Here is the very basic code snippet i'm working with:
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "User Id=XXXXXX;Host=localhost;Database=XXXXXX";
SqlCommand insertCommand = new SqlCommand("INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1, 72, 34)", conn);
}
}
}
}
I am using Visual Studio 2017, DotConnect for MySQL, MySQL server, and Wamp Connect. Thank you!
EDIT: After reading documentation a sample c# program with this format should look like
using System;
using System.Windows.Forms;
using Devart.Data.MySql;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("User Id=root;Host=localhost;Database=XXXXXX;");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1,73,32)";
cmd.Connection = conn;
conn.Open();
try
{
int aff = cmd.ExecuteNonQuery();
MessageBox.Show(aff + " rows were affected.");
}
catch
{
MessageBox.Show("Error encountered during INSERT operation.");
}
finally
{
conn.Close();
}
}
}
}
The key is to not only use the correct reference but to also download the correct package on nuget. Easy to forget for beginners!
What??? you are using DotConnect for MySQL but you use a SqlConnection class. That's the issue here cause SqlConnection is for SQLServer. You should use using Devart.Data.MySql.MySqlConnection instead.
using (SqlConnection conn = new SqlConnection())
{
Check the documentation first which says everything. https://www.devart.com/dotconnect/mysql/docs/
In login form, When I login as Jack which exist in the DOCTOR table, it will go to page_two. I want to pop up a access denied message if nurse button 1 or nurse button 2 is clicked since Jack is not a nurse but a doctor. Then for the opposite, if I login as Mary, which exist in the NURSE table, it will go to page_two. I want to pop up a access denied message when doctor button 1 or doctor button 2 is clicked since Mary is not a doctor but a nurse.
The button names for Page_two is btnDoctor1, btnDoctor2, btnNurse1 and btnNurse2
**//login Form codes**
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace GRP_02_03_SACP
{
public partial class page_one : Form
{
public page_one()
{
InitializeComponent();
}
private void page_one_Load(object sender, EventArgs e)
{
}
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
}
}
//Page_two codes
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
public page_two()
{
InitializeComponent();
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}
Add This To your Code :
public Int JobPosition;
Here you will Define the position for each.
Change the Code on your btnLogin_Click to this :
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 1; //Doctor
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 2; //Nurse
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
On Page_two Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
private Int JopPosition;
public page_two()
{
InitializeComponent();
}
public page_two(Int _Position)
{
InitializeComponent();
JopPosition = _Position;
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
if (JopPosition == 1)
{
MessageBox.Show("access denied");
}
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}