Cannot send data to my DB - c#

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);

Related

Retrieve Auto Increment ID from SQL Database after Insert Statement

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?

How can I avoid having duplicate data in my database?

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;
}
}
}

Query Runs in Ms Access Database But Not When Executed From Application

Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}

How to add data into Specified columns in mysql using c#

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();
}
}

How Do I Populate Text Boxes With Sql Database Data Using One Combo Box

Hey everyone pretty new to SQL Database functions but have been coding in c# for about a year now still not that great at it but I'm getting there!
I'm currently creating a football application and to Edit players and Matches i was wanting to use one drop down combo box to retrieve data from an SQL database which then would populate other text boxes and combo boxes. I've had a go at it myself but don't know where i'm going wrong.
On form load my connection opens i populate my datasets and i execute this method to populate my combobox
private void Navigate()
{
string showPlayers = "SELECT * From Add_Players";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayer.Items.Add(myReader[0]);
}
conn.Close();
}
After which in the combo box selected index changed method i have this code
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='"
+ comboEditPlayer + "' ;";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
conn.Close();
conn.Dispose();
}
catch (Exception comboFail)
{
MessageBox.Show(comboFail.ToString());
}
}
I've been told this code is open and i need to use parameterized queries for preventing hacker attempts which i have started but do not know what Parameter i should be adding to the code i have for this is below
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID ="
+ comboEditPlayer.SelectedValue + "", connection))
{
command.Parameters.Add(new SqlParameter ("",));
}
}
}
All help is appreciated and please go easy on me :P
You could add a parameter to the collection with the value of your ComboBox, then execute the query and read back the values from the reader
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID =#id", connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", comboEditPlayer.Text);
using(SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
}
}
}

Categories

Resources