I have a databse where the user can track new models coming into shop but they only keep one of each model, I'm not sure how to stop the user from repeating the same model. I've seen some previous answers on this site but I'm getting errors when using the code in my own.
private void check_Click(object sender, EventArgs e)
{
string query = "INSERT INTO tbl_phones(model) VALUES(#model)";
using (SqlConnection sqlconn = new SqlConnection(#""))
using (SqlCommand comm = new SqlCommand(query, sqlconn))
{
sqlconn.Open();
comm.Parameters.Add("#model, SqlDbType.NVarChar).Value = phoneinput.Text;
comm.ExecuteNonQuery();
This should work (get a count of phones where model is entered, if is less than one then insert).
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(#model)";
string checkQuery = "SELECT COUNT(*) FROM tbl_phones WHERE model = #model";
using (SqlConnection sqlconn = new SqlConnection(#""))
{
sqlconn.Open();
SqlCommand checkCommand = new SqlCommand(checkQuery, sqlconn);
checkCommand.Parameters.AddWithValue("#model", phoneinput.Text);
if((int)checkCommand.ExecuteScalar() < 1)
{
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("#model", phoneinput.Text);
insertCommand.ExecuteNonQuery();
}
}
}
Edit - if you decide to set model to be a primary key, you can catch the exception like so -
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(#model)";
using (SqlConnection sqlconn = new SqlConnection(connectionString))
{
sqlconn.Open();
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("#model", "test");
try
{
insertCommand.ExecuteNonQuery();
}
catch(SqlException ex)
{
if (ex.Number == 2627)
{
// Phone already exists, do some stuff
}
else throw;
}
}
}
Related
Below here is my code to Retrieve Auto Increment ID After Inserting data into database.
However, I am getting Auto Increment ID before Inserting data into database.
How can I get auto increment ID after insert into database?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RetrievePRReqID();
}
}
//Retrieve ID method
private void RetrievePRReqID()
{
try
{
string query = "Select IDENT_CURRENT('tblPRRequest')";
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand cmd = new SqlCommand(query, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
int value = int.Parse(reader[0].ToString()) ;
txt_PRNO.Text = value.ToString();
}
}
catch(Exception)
{
throw;
}
finally
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
}
//Request button Method
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
}
By referring sample answer from #Mx.Wolf, I modified a bit to get the right answer, below here is the codes that is working :
protected void btn_Request(object sender, EventArgs e)
{
object id ;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.PRReqID " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
As stated in SQL Server documentation
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15
The OUTPUT clause may be useful to retrieve the value of identity or computed columns after an INSERT or UPDATE operation.
You have to change your SQL statement
INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName)
OUTPUT inserted.ID
-------^^^^^^^^_^^
VALUES (#RequestTo,#RequestFrom,#RequestedByName)
and now you can use ExecuteScalar to get the inserted value
protected void btn_Request(object sender, EventArgs e)
{
int id= 0;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.ID" +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = (int)sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
}
Try this:
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output;
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
sqlcmd.Parameters["#ID"].value; // Access it like this
}
In case you can chage the ExecuteNonQuery to ExecuteScalar, then it would be even easier: What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?
I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.
I want to insert my dropdownlist and my textbox values to my database stored procedure but it doesn't insert and also doesn't give me any error. Any ideas what I am doing wrong?
protected void btnPlaceScores_Click(object sender, EventArgs e)
{
string conn = WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;
using (SqlConnection myconnection = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("MatchScores", myconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("HomeTeam", drop1.SelectedItem.Value);
cmd.Parameters.AddWithValue("AwayTeam", drop2.SelectedItem.Value);
cmd.Parameters.AddWithValue("Scores", txtScores.Text);
try
{
myconnection.Open();
cmd.ExecuteNonQuery();
}
catch { }
finally
{
myconnection.Close();
}
}
}
Not sure if you're using Microsoft SQL, normally parameters start with an '#'
cmd.Parameters.AddWithValue("#HomeTeam", drop1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#AwayTeam", drop2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Scores", txtScores.Text);
I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.
How to add data into Specified columns in mysql database table using c# button click, once i clicked the button it will be passing to the catch
here is my add button code
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES ("
+ this.depIDInput.Text + ",'"
+ this.depnameInput.Text + "','"
+ this.dep_branchIDInput.Text + "')";
//This is command class which will handle the query and connection object.
MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();// Here our query will be executed and data saved into the database.
conn.Close();
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
here is all the columns of the table,
INSERT INTO `bcasdb`.`tbl_student`
(`reg_id`,
`std_fname`,
`std_lname`,
`tbl_batch_batch_id`,
`gender`,
`dob`,
`email`,
`mobile`,
`contact_address`,
`home_address`,
`status`,
`course_id`,
`depart_id`,
`parent_name`,
`telephone`,
`nationality`,
`nic`,
`passport_no`,
`acadamic_qulification`,
`current_employement`,
`gce_ol`,
`gce_al`,
`birth_certifiacte`,
`copy_of_nic`,
`police_clerence`,
`tbl_studentcol`)
VALUES
I believe your code should be rewritten as following:
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES (#depId, #depName, #branchId)";
//This is command class which will handle the query and connection object.
using (MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(Query, conn))
{
cmd.Parameters.Add("#depId", this.depIDInput.Text);
cmd.Parameters.Add("#dep_name", this.depnameInput.Text);
cmd.Parameters.Add("#branchId", this.dep_branchIDInput.Text);
cmd.ExecuteNonQuery();
}
}
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}