C# program does not connect to a database (freesqldatabase.com) - c#

I'm using freesqldatabase.com to get a database for a college project, so having a remotely accessible database is needed. Unfortunately it does not connect to the database. It connects to their myphpadmin just fine but any other connection fails.
private void Submit_registration(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source= sql2.freesqldatabase.com; Initial Catalog=dbname; User ID=id;Password=no, Integrated Security= True;");
sqlCon.Open();
String query = "INSERT INTO tbluser (ID, username, password) VALUES (#ID, #username, #password)";
String query2 = "SELECT MAX(ID) FROM tbluser";
SqlCommand cmd2 = new SqlCommand(query2, sqlCon);
SqlCommand cmd = new SqlCommand(query, sqlCon);
int maxId = Convert.ToInt32(cmd2.ExecuteScalar());
int newmaxid = maxId + 1;
if (String.Equals(text_password.Password,text_password_confirm.Password))
{
cmd.Parameters.AddWithValue("#ID", newmaxid.ToString());
cmd.Parameters.AddWithValue("#username", textbox_username.Text);
cmd.Parameters.AddWithValue("#password", text_password.Password);
cmd.ExecuteNonQuery();
sqlCon.Close();
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
Close();
}
else
{
MessageBox messageBox = new MessageBox();
messageBox.Show();
sqlCon.Close();
}
}

Related

C# update combobox with Database values

Hello I have a database with drivers and a combobox which is populated with the drivers. But when I add a new driver with a button Add Driver, it's added only in Microsoft Access table, not in the combobox. And once I reload the program, the new driver is deleted from the database. I also have connected the database in Data Source and I can edit the tables only from there(if I want to edit the combobox).
This is my connection with the database
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
cmd = new OleDbCommand();
con.Open();
cmd.Connection = con;
string query = "SELECT Name FROM Drivers";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboDriver.Items.Add(reader["Name"]);
}
con.Close();
and this is my Add Driver button:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
String Id = textID.Text;
String Name = textName.Text;
String Age = textAge.Text;
String City = textCity.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Drivers (Id, Name, Age, City) Values(#Id, #Name, #Age, #City)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Id", OleDbType.VarChar).Value = Id;
cmd.Parameters.Add("#Name", OleDbType.VarChar).Value = Name;
cmd.Parameters.Add("#Age", OleDbType.VarChar).Value = Age;
cmd.Parameters.Add("#City", OleDbType.VarChar).Value = City;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("New Driver Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
Just because you've added it to your database, doesn't mean anything else will happen.
You still need to update your UI.
Add this in after you have executed the query:
comboDriver.Items.Add(Name);
As an aside, you should also wrap the conn.Open() in a try catch as well

updating sql server database using c# in asp.net

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.

windows form how to check in database if user already exist?

I want to create a simple form where I want to validate to show message if same users exists.
The function usernamecheck() checks for validation and displays error if same user exists but when I click submit button it still submits same user.
private void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
UserNameCheck();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
public void UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
break;
}
}
}
Problem : You are Inserting the record always without check wether user exist or not.
Solution :
You need to return the boolean value from the UserNameCheck() function.
retrun true if username exist.
return false if username doesnot exist.
then execute the Insert Query if and only if UserNameCheck function returns false
Try This:
Chnage the UserNameCheck() function code as below to return the boolean value.
public bool UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select count(*) from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
int TotalRows = 0;
TotalRows = Convert.ToInt32(cmd.ExecuteScalar());
if(TotalRows > 0)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
return true;
}
else
{
return false;
}
}
Now Change the Submit function code to verify the UserNameCheck() return value, proceed to the insertion only if the UserNameCheck() function returns false(when user does not exist)
private void submit_Click(object sender, EventArgs e)
{
if(!UserNameCheck())
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
}
First fire a select query that checks whether a user exists or not. If not then fire insert statement.
you should make a select count by name for the user first, and if the counter is bigger than 0 make the insert

Emp timeout time not saving in database

I am making emp time attendance register. I am using below code .. here insert query working fine and time-in successfully save in database timein field. Update query also execute successfully but databasae not updated...anyone please help for this...
private void checkin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into timeatten (id,name,timein)values('" +comboBox1.Text+"','"+textBox1.Text+"','"+textBox2.Text+"' )";
comm.Connection = conn;
comm.ExecuteNonQuery();
MessageBox.Show("Successfully check in");
conn.close();
}
private void checkout_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source.............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "update timeatten set timeout='" + textBox2.Text + "' where id='" + comboBox1.Text +"'";
MessageBox.Show("Successfully Checkout");
conn.close();
}
I think you're missing these two lines in checkout_Click:
comm.Connection = conn;
comm.ExecuteNonQuery();

Check if username existed in SQLExpress

Error shows : ExecuteScalar: Connection property has not been
initialized and exists = (int)cmd.ExecuteScalar() > 0;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)");
try
{
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
connection.Open();
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
}
What should be the correct way to declare the connection first because I tried to put it before but I'm having problems with the cmd.
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
You need to assign the connection to the command in your last example
So within your using statement add:
cmd.Connection = connection;
Additionally you don't need:
SqlCommand cmd;
as the command is created within the context of that using statement.
It's also considered good practice to wrap the Connection context within a using statement to ensure the actual connection get's disposed / closed correctly.
Try this,
using (SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
bool exists = (int)cmd.ExecuteScalar() > 0;
}
You didn't specified connection to command. Secondly you have to open connection.
Update: Complete Code
try
{
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
bool exists = false;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)", Connection);
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
//Do something
}
finally
{
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
SQL command should have a overload which takes an initiated connection
Use SqlCommand constructor that takes connection as second argument. Next you have to open it before executing command and after that close it.
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
connection.Open();
exists = (int)cmd.ExecuteScalar() > 0;
connection.Close();
}

Categories

Resources