C# Syntax Error in INSERT INTO statement C# - c#

if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp

Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";

Related

Check if same username exists in sql server management..... if so dont add the username

It is showing me 2 errors.. please help .....required for my project work
The error showing in both cases is as follows:-
Error 1 'System.Data.SqlClient.SqlDataAdapter' does not contain a
definition for 'loginregistration' and no extension method
'loginregistration' accepting a first argument of type
'System.Data.SqlClient.SqlDataAdapter' could be found (are you missing
a using directive or an assembly reference?)
private void btnSave_Click(object sender, EventArgs e)
{
{
if (txtUsername.Text == "" || txtEmail.Text == "")
{
MessageBox.Show("Please enter all Details");
}
else
{
SqlCommand cmd = new SqlCommand("select * from loginregistration WHERE username='" + txtUsername.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = da.loginregistration[0].Rows.Count;//.........(ERROR HERE)
if (i > 0)
{
MessageBox.Show("Username Already Exists");
da.Clear();//............(ERROR HERE)
}
else
{
try
{
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into loginregistration(username,FirstName,LastName,Email,Address,Contact_No) VALUES('" + txtUsername.Text + "','" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtAddress.Text + "','" + txtContact.Text + "')";
cmd1.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Inserted Successfully");
txtUsername.Text = txtFirstName.Text = txtLastName.Text = txtEmail.Text = txtContact.Text = txtAddress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("ex.Message");
}
}
}
}
}
Let's extract a method for checking user's existence. We don't need to load all the data into a DataTable with a help of SqlDataAdapter; one query will be enough:
private bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection("Connection_String_Here")) {
conn.Open();
// Keep query readable
// Make query parametrized
string sql =
#"select 1
from LoginRegistration
where UserName = #prmUserName";
// Do not share the single connection, but create a new one
using (SqlCommand q = new SqlCommand(sql, conn)) {
q.Parameters.Add("#prmUserName", SqlDbType.VarChar).Value = userName;
// If we can read at least one record
using (var reader = q.ExecuteReader()) {
// we can be sure the user exists
return reader.Read();
}
}
}
}
Now, let's use our method:
if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtEmail.Text))
MessageBox.Show("Please enter all Details");
else {
if (UserExists(txtUsername.Text))
MessageBox.Show("Username Already Exists");
else {
...
}
}
try to use dataset
DataSet loginregistration = new DataSet();
da.Fill(loginregistration ,"loginregistration ");
To fix your existing code:
int i = da.loginregistration[0].Rows.Count;
should be
int i = ds.Tables[0].Rows.Count;
That said you should pay attention to the answer Dmitry gave and parameterise your SQL. Your current method is wide open to SQL Injection.

I am working on a New user registration form that only contains of 3 fields, Username, password and confirm password

I am working on a user registration form containing only 3 fields Username,password and confirm password. But when i insert data, if password is mismatching, the exception appears form mismatch but on clicking OK, the data is inserted into db.
what should i do that it only insert on matching password
private void btn_save_Click(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
string query = "INSERT INTO Users (username,newpassword)values('" + txt_newusr.Text + "','" + txt_password.Text + "')";
if (txt_password.Text == "" || txt_cnfpw.Text == "")
{
MessageBox.Show("Please enter values");
return;
}
if (txt_password.Text != txt_cnfpw.Text)
{
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
conn.Close();
}
}
You should change it like that
if (txt_password.Text == txt_cnfpw.Text)
{
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
}
You have to do lots of corrections to make this work properly, Corrections like the following:
Make use of parameterized queries instead for concatenated queries to avoid injection
Process insert only after client-side validations(empty check password match etc)
Make use of using for managing connections and commands
I have added an example below, please have a look
try
{
string query = "INSERT INTO Users (username,newpassword)values(#username,#newpassword)";
bool CanInsertNewUser = true;
if (txt_newusr.Text=="" || txt_password.Text == "" || txt_cnfpw.Text == "")
{
CanInsertNewUser = false;
MessageBox.Show("Please enter values");
}
if (txt_password.Text != txt_cnfpw.Text)
{
CanInsertNewUser = false;
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}
if (CanInsertNewUser)
{
using (OleDbConnection conn = new OleDbConnection("GiveYourConnectionStringHere"))
{
using (OleDbCommand command = new OleDbCommand())
{
conn.Open();
command.Connection = conn;
command.CommandText = query;
command.Parameters.Add("#username", OleDbType.VarChar).Value = txt_newusr.Text;
command.Parameters.Add("#newpassword", OleDbType.VarChar).Value = txt_password.Text;
command.ExecuteNonQuery();
}
}
MessageBox.Show("Success");
}
}
catch (Exception ex)
{
MessageBox.Show("OLEDB issues : " + ex.Message.ToString());
}
In both the success and failure cases you are attempting to commit the transaction.
Save statements should only be executed if the password is matching. Move the save statements inside the success block as follows.
if (txt_password.Text == txt_cnfpw.Text)
{
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
}
else
{
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}

C# SQL Connection string " can't find the table "

Currently I'm working on a project that generates files....().
Everything seems to work well. I can connect to the database and my methods of reading and writing are working, too, but I can't find the table. I have an error:
$exception {"Invalid object name 'T_SAL'."} System.Data.SqlClient.SqlException
I don't know if the problem is with my connection string or something else!
Is there anyone that can help me with this, please?
My methods' code:
//SQL connection Methods**
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
{
try
{
SqlConnection conn = new SqlConnection();
String Securité;
if (Authentification)
{
Securité = "Integrated Security = true";
}
else
{Securité = "User Id =" + SQL_LOGIN + ";" + "Password =" + SQL_PASSWORD;}
conn.ConnectionString = "Data Source=" + SQL_SERVER + ";Initial Catalog=" + BASE_CONSOLE + ";" + Securité + ";";
conn.Open();
return conn;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return null;
}
// Generation :
private void Gen_f_Click(object sender, EventArgs e)
{
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
if (conn == null)
{
MessageBox.Show("Connexion impossible");
return;
}
try
{
//traitement du fichier des salaeiés
var lines = Methodes.lecture(fp_text.Text);
foreach (var ligne in lines)
{
string[] cols = ligne.Split(char.Parse(";"));
string Matricule = cols[0];
if (Matricule != "" && MatriculeExiste(conn, Matricule) == false)
{
string ligneSorties = "";
ligneSorties = ligneSorties + cols[0] + ";";
Methodes.Ecriture(ligneSorties, "fp_sorties.'Text'", true);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private bool MatriculeExiste(SqlConnection conn, string Matricule)
{
SqlCommand command = new SqlCommand("SELECT MatriculeSalarie FROM [T_SAL] WHERE MatriculeSalarie='" + Matricule + "'", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return true;
}
else
{
return false;
}
}
}
The issue seems to be in the order of parameters that you pass to OpenSql method:
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
This is how you call it:
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
There is definitely some mismatch with the order of parameters, your declaration expects SQL_Login, SQL_PASSWORD, SQL_SERVER, BASE_CONSOLE and you are passing SQL_SERVER, BASE_CONSOLE, SQL_LOGIN, SQL_PASSWORD
So if you use Windows Authentication, it would work, because you are not passing login and password, but instead of correct Database Name you are passing password, so your user ends up into Master db, which does not contain required table.

Select MySQL Data in C#

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin.
This is what I have so far.
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection connection;
string server = "localhost";
string database = "login";
string uid = "root";
string password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
connection.Close();
Form1 frm = new Form1(this);
frm.Show();
Hide();
}
else
{
MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
catch (Exception ex)
{
MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered.
I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.
You can use this way to see if username and password match
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = #username and password=#password";
command.Parameters.Add("#username", txtUserName.Text);
command.Parameters.Add("#password", txtPassword.Text);
var count = cmd.ExecuteScalar();
if(count>0)
//Logged In
Just to say, if you use a query like
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";
You will be open to SQL Injection
Warning
As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation
you make try this one
using(var con = new MysqlConnection{ ConnectionString = "your connection string " })
{
using(var command = new MysqlCommand{ Connection = con })
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE username=#username, password=#password";
command.AddWithValue("#username", txtusername.Text);
command.AddWithValue("#password", txtpassword.Text);
var strLevel = myCommand.ExecuteScalar();
if(strLevel == DBNULL.Value || strLevel == Null)
{
MessageBox.Show("Invalid username or password");
return;
}
else
{
MessageBox.Show("Successfully login");
hide(); // hide this form and show another form
}
}
}
use below Query
Select * from UsersTable Where Username='"+username+"' AND password='"+password+"'
Then you can make a if condition that if your query contain a result (rows) then users authenticated (exists in Table)
Note:Select query may fetch multiple users having same userName and
password, its upto you to keep usersname unique in table

update data using oledb in c#

I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}

Categories