I want to add a Serial No. on the first column in the MySQL table in my C# program. To do this automatically with every row entry, I need to count previous rows and '+1' with the result.
How to count numbers of rows present in a column in MySQL with C#?
This is the code I am using now:
private void button2_Click(object sender, EventArgs e)
{
string connection = "datasource=localhost;port=3306;username=root;password=root";
string Query = "insert into database.accounts (idaccounts,Name,EmailID,UserID,Password,DOB,Gender) values('" +3+ "','" + this.AddUserName.Text + "','" + this.AddEmail.Text + "','" + this.AddUserID.Text + "','" + this.AddPassword.Text + "','"+this.dateTimePicker.Text + "','" + Gender + "') ;";
MySqlConnection conData = new MySqlConnection(connection);
MySqlCommand cmdData = new MySqlCommand(Query, conData);
MySqlDataReader myReader;
try
{
conData.Open();
myReader = cmdData.ExecuteReader();
MessageBox.Show("User Added Successfully!");
while(myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to add the Serial No. in the idaccounts column automatically with every new entry.
Related
I'm doing a registration form in c#
the code is working really well, but the the problem is even if the username
is already exist in the database it's still able to duplicate username.
How can i add a restriction for having a duplicate value for username?
So here is my code ps. i didn't add the exception because it's too long.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
while (myReader.Read())
{
}
}
You need to add a unique limitation (constraint) to your table, using whatever database editor you used to create it. Then, catch an exception thrown by your application if the username is taken.
Basically, if there is some username already there, and you have a unique constraint on the username field in the table, your program will throw an exception when you try to add to it. Here is an example:
Also, if you are doing an insert query, you don't need to ExecuteRead(). Just do ExecuteNonQuery() and it will run the query without needing to return anything.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
try {
cmdDatabase.ExecuteNonQuery();
}
catch {
//Username is taken
}
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
I'm using textbox to insert the data to the database. However I don't want to insert null or empty value to the database. How can I use if-statement to check the textbox is empty? (which means if the textbox is empty, show a dialog to required user input data)
Here is my code:
private void submit_button_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;username=root;password=";
string Query = "INSERT INTO bug.bug (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "')";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can use string.IsNullOrEmpty or string.IsNullOrWhiteSpace methods for checking if string is empty or only containts white spaces.
You should also avoid joining query using +. Use paratrized queries better. Example.
Try like this:
if (string.IsNullOrWhiteSpace(MyTextBox.Text))
{
//some message
}
This will handle the whitespace also (if it is present in your text box.)
On a side note:
Your code is prone to SQL Injection. You should better try to use parameterized query to handle it.
Put this condition in the start of your method
if(string.IsNullOrWhiteSpace(TextBox1.Text))
{
MessageBox.Show("Empty value");
return;
}
Use like following. Hope it will solve your problem
if(!string.IsNullOrEmpty(txtYourTextBox.Text))
{
//Logic here if text box is not empty
}
Be ware of Sql Injection
private void submit_button_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(mytextBox))
{
MessageBox.Show("your message goes here");
return ;
}
string constring = "datasource=localhost;username=root;password=";
// insert with parameterised query
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am getting an error that i dont understand. I have a form where a new row has to be added when i press the button add. It has to check for the values in comboBox cb_Character and from comboBox cb_Talents. When i test it i get the error. Data too Long for column, however when i try it in Mysql i am able to do it. what is wrong?
private void btn_addTalent_Click(object sender, RoutedEventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=Lorena89;";
string Query = "SET foreign_key_checks = 0; INSERT INTO dark_heresy.learned_talents (Character_Name, Talent_Name) VALUES ('" + cb_Character + "','" + cb_Talents + "'); SET foreign_key_checks = 1; ";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Added Talent to Character");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
I found the error, i was missing the .Text
('" + cb_Character.Text + "','" + cb_Talents.Text + "');
I have a Form that contains an "Add" button and a textBox, which is used to add information to a database table.
I need to check if the code entered in the TextBox is available before I can insert it.
My problem is that I get errors, as it attempts to add a "duplicate primary key" and I'm unsure of the source of error.
Below is the code I currently have:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
String reqt1="select numero_cpte from compte where numero_cpte="+textBox1.Text+";";
SqlCommand sql1 = new SqlCommand(reqt1, connection1);
int d = int.Parse(textBox1.Text);
int dd = Convert.ToInt32(sql1.ExecuteScalar());
if(d == dd)
{
int o1 = sql1.ExecuteNonQuery();
MessageBox.Show("this account is not valide!!","Fiche ");
connection1.Close();
}
if (String.IsNullOrEmpty(textBox1.Text) == true)
{
MessageBox.Show("You should insert the code!!","Fiche",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand sql = new
SqlCommand("insert into compte values(" + textBox1.Text + ",'" +
textBox2.Text + "','" + type_cpteComboBox.SelectedItem.ToString() +
"','" + textBox2.Text + "','" + comboBox1.SelectedItem.ToString() +
"'," + comboBox2.SelectedItem.ToString() + ",'" +
checkBox1.Checked.ToString() + "','" + checkBox2.Checked.ToString() +
"','" +textBox5.Text+ "','" +textBox6.Text+ "');", connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + "Success of add","Fiche");
connection.Close();
textBox1.Text = "";
textBox2.Text = "";
}
This is the error I see:
The insert command works perfectly, but When I try to test if the code that I'am going to add in the base exists or not (by typing a code that I know exists), I get this exception.
It looks like your code drops down into the add code even if you have discovered that your number is a duplicate. Try adding "return;" after you close the connection.
MessageBox.Show("Ce compte existe.Veuillez sasir un numéro de compte valide!!", "Fiche Comptes");
connection1.Close();
return;
private object ExecuteScalar(string sql)
{
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
SqlCommand sql1 = new SqlCommand(sql, connection1);
return sql1.ExecuteScalar();
}
}
The advantage of this is that you always know that your connection will be closed when you are done. Even if you are only going to be calling this method once, it improves readability and is therefore helpful.