I have to insert into two tables (contact and patient) using one transaction. The insert into the contact table works fine, although it is incrementing the contactID by 2. For example, if the most recently added row has a contactID of 25, this method will insert a new row with a contactID of 27. However, the insert into the patient table does nothing at all. The patient table is comprised of only two columns:
patientID INT PRIMARY KEY
contactID INT FOREIGN KEY
The contactID column in the patient table references the contactID column in the contact table. Since the insert is done into the contact table first, I'm not sure why there would be any problems.
public static bool CreatePatient(string lName, string fName, DateTime dob, string streetAddress, string city, string state, string zip, string phone, string gender, string ssn)
{
bool isCreated = false;
int newContactID = 0;
string insertStmt1 = "INSERT INTO contact (lName, fName, dob, mailingAddressStreet, mailingAddressCity, mailingAddressState, mailingAddressZip, phoneNumber, gender, SSN, userType) " +
"VALUES (#last, #first, #dob, #street, #city, #state, #zip, #phone, #gender, #ssn, 4)";
string selStmt = "SELECT MAX(contactID) AS MaxContactID FROM contact";
string insertStmt2 = "INSERT INTO patient (contactID) VALUES (#contact);";
using (SqlConnection connect = DBConnection.GetConnection())
{
connect.Open();
SqlTransaction tran = connect.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand(insertStmt1, connect, tran))
{
cmd.Parameters.AddWithValue("#last", lName);
cmd.Parameters.AddWithValue("#first", fName);
cmd.Parameters.AddWithValue("#dob", dob);
cmd.Parameters.AddWithValue("#street", streetAddress);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#zip", zip);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#ssn", ssn);
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(selStmt, connect, tran))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
newContactID = (int)reader["MaxContactID"];
}
}
}
if (newContactID > 0)
{
using (SqlCommand cmd = new SqlCommand(insertStmt2, connect, tran))
{
cmd.Parameters.AddWithValue("#contact", newContactID);
cmd.ExecuteNonQuery();
}
}
isCreated = true;
tran.Commit();
connect.Close();
}
catch
{
tran.Rollback();
return false;
}
}
return isCreated;
}
public static List<Patient> SearchPatientByFirstAndLastName(string fName, string lName)
{
List<Patient> patientList = new List<Patient>();
string selectStatement = "SELECT * FROM contact INNER JOIN patient ON contact.contactID = patient.contactID "
+ "WHERE contact.fName LIKE '%'+#fName+'%' AND contact.lName LIKE '%'+#lName+'%'";
try
{
using (SqlConnection connection = DBConnection.GetConnection())
{
connection.Open();
using (SqlCommand selectCommand = new SqlCommand(selectStatement, connection))
{
selectCommand.Parameters.AddWithValue("#fName", fName);
selectCommand.Parameters.AddWithValue("#lName", lName);
using (SqlDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
Patient patient = new Patient();
patient.PatientID = (int)reader["patientID"];
patient.ContactID = (int)reader["contactID"];
patient.LastName = reader["lName"].ToString();
patient.FirstName = reader["fName"].ToString();
patient.Dob = (DateTime)reader["dob"];
patient.Address = reader["mailingAddressStreet"].ToString();
patient.City = reader["mailingAddressCity"].ToString();
patient.State = reader["mailingAddressState"].ToString();
patient.Zip = reader["mailingAddressZip"].ToString();
patient.Phone = reader["phoneNumber"].ToString();
patient.Gender = reader["gender"].ToString();
patient.Ssn = reader["ssn"].ToString();
patientList.Add(patient);
}
reader.Close();
}
}
connection.Close();
}
}
catch (SqlException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
return patientList;
}
EDIT
I am now trying a different approach. Instead of handling this all in the program, I created a stored procedure as follows:
CREATE PROCEDURE [dbo].[uspCreatePatient] #last VARCHAR(45), #first VARCHAR(45), #dob DATE, #street VARCHAR(100), #city VARCHAR(100), #state CHAR(2), #zip CHAR(5),
#phone VARCHAR(20), #gender CHAR(1), #ssn CHAR(9), #isCreated BIT OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #contact INT;
BEGIN TRAN
BEGIN TRY
INSERT INTO contact (lName, fName, dob, mailingAddressStreet, mailingAddressCity, mailingAddressState, mailingAddressZip, phoneNumber, gender, SSN, userType)
VALUES (#last, #first, #dob, #street, #city, #state, #zip, #phone, #gender, #ssn, 4);
SET #contact = SCOPE_IDENTITY();
INSERT INTO patient (contactID) VALUES (#contact)
COMMIT TRAN
SET #isCreated = 1;
END TRY
BEGIN CATCH
ROLLBACK TRAN
SET #isCreated = 0;
END CATCH
END
I then updated the CreatePatient method in C# as follows:
public static bool CreatePatient(string lastName, string firstName, DateTime dob, string streetAddress, string city, string state, string zip, string phone, string gender, string ssn)
{
int result = 0;
bool isCreated = false;
using (SqlConnection connect = DBConnection.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("uspCreatePatient", connect))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#last", lastName);
cmd.Parameters.AddWithValue("#first", firstName);
cmd.Parameters.AddWithValue("#dob", dob);
cmd.Parameters.AddWithValue("#street", streetAddress);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#zip", zip);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#ssn", ssn);
result = cmd.ExecuteNonQuery();
}
}
if (result == 1)
{
isCreated = true;
}
return isCreated;
}
However, the same problem is happening. Only the contact table is being updated. When I run these same commands in SQL Server with hardcoded values, both tables are updated like I want.
Related
I've created a stored procedure in SQL Server to check if username exists in the database:
CREATE PROCEDURE [dbo].[spCheckUsernameForAnswer]
#username VARCHAR(30)
AS
BEGIN
DECLARE #count INT
SELECT #count = COUNT(username)
FROM Users
WHERE [username] = #username
IF (#count = 1)
BEGIN
SELECT 1 AS ReturnCode
END
ELSE
BEGIN
SELECT 0 AS Returncode
END
END
Here is what I've done in Visual Studio Registration.aspx.cs.
I need to check if the username exists and if not to insert the required values into db to register a new user.
From the code below it keeps registering new users with the same username again and again.
Any idea what am I missing here?
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("spCheckUsernameForAnswer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parausername = new SqlParameter("#username", TextBoxUN.Text);
cmd.Parameters.Add(parausername);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReturnCode"]))
{
Label1.Text = "Username found";
}
else
{
Label1.Text = "not found";
}
}
conn.Close();
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn1.Open();
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn1);
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Write("Registration successful");
conn1.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
It's better use cmd.ExecuteScalar since the sp is returning either 1 or 0.
And it would be better to have the insert into db part in a separate method like RegisterUser method.
But the main thing is you need to call that method when it doesn't exist in db (in the else statement)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using(var cmd = new SqlCommand("spCheckUsernameForAnswer", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#username", TextBoxUN.Text));
conn.Open();
var returnCode = Convert.ToInt32(cmd.ExecuteScalar());
if(returnCode == 1)
{
Label1.Text = "Username found";
}
else
{
Label1.Text = "not found";
Register();
}
}
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
private void RegisterUser()
{
try
{
var newGUID = Guid.NewGuid();
using(var conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
conn1.Open();
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
using(var com = new SqlCommand(insertQuery, conn1))
{
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
}
}
Response.Write("Registration successful");
}
catch (Exception exc)
{
//log the exception;
}
}
Try this not too sure why you used reader if i was you will handle everything in stored procedure
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("spCheckUsernameForAnswer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parausername = new SqlParameter("#username", TextBoxUN.Text);
cmd.Parameters.Add(parausername);
conn.Open();
var userexsist = (bool)cmd.ExecuteScalar();
if (userexsist)
{
Label1.Text = "Username found";
conn.close();
}
else
{
Label1.Text = "not found";
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Write("Registration successful");
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You can manage it in stored procedure also. Find the solution:
USE [akhil_db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Sp_Insert_AddUser]
(
#fname varchar(200),
#lname varchar(200),
#userName varchar(200),
#userEmail varchar(200),
#userPasword varchar(200),
#userType varchar(200),
#msg VARCHAR(100) OUT )
AS
BEGIN
SET NOCOUNT ON;
Declare #UserCount int;
SELECT #UserCount = COUNT(*) FROM user_master WHERE [user_name] = #userName or [user_email]=#userEmail;
IF(#UserCount > 0)
begin
Set #msg = 'User already exists';
end
ELSE
begin
Insert into user_master(
user_fname,
user_lname,
[user_name]
,[user_email]
,[user_pasword]
,user_type
)
values(
#fname,
#lname,
#userName
,#userEmail
,#userPasword
,#userType
)
SET #msg ='Registered Successfully'
END
END
Code behind c#
SqlCommand cmd = new SqlCommand("Sp_Insert_AddUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#fname", txtfname.Text);
cmd.Parameters.Add("#lname", txtlname.Text);
cmd.Parameters.AddWithValue("#userName", txtUserName.Text);
cmd.Parameters.AddWithValue("#userEmail", txtUserEmail.Text);
cmd.Parameters.AddWithValue("#userPasword", txtPass.Text);
cmd.Parameters.AddWithValue("#userType", ddlUserType.SelectedValue);
cmd.Parameters.Add("#msg", SqlDbType.Char, 500);
cmd.Parameters["#msg"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
string message = (string)cmd.Parameters["#msg"].Value;
lblMessage.Visible = true;
lblMessage.Text = message;
con.Close();
I'M USING HELPER CLASS VS. SOON I WILL SENT ALTERNATIVE SOLUTION
SqlHelper sho = new SqlHelper();
public bool alreadyexist()
{
string[] str = { "#catname", "#proname" };
string[] obj = { comboproductname.Text, comboitemname.Text };
SqlDataReader sdrr = sho.GetReaderByCmd("sp_item_alreadyex", str, obj);
if (sdrr.Read())
{
sdrr.Close();
sho.CloseConnection();
return true;
}
else
{
sdrr.Close();
sho.CloseConnection();
return false;
}
Stored procedure:
Create procedure [dbo].[sp_item_alreadyex]
#catname nvarchar(50),
#proname nvarchar(50)
as
begin
select *
from Item
where Item_Name = #proname and Category = #catname
end
Hey guys i need help on this one. What I'm trying to do here is to check my mysql db if a member already exists using the name of the member based on the data entry on my winform. The verification for duplicate entry works, shows the messagebox perfectly the way i want, but it doesn't execute the insert query i made in case no existing member is found.
Am I doing this correctly? or is there another way to get it working the way i want.
Here is my code:
private void metroButton1_Click(object sender, EventArgs e) {
using (con = new MySqlConnection(constring)) {
string selectquery = "SELECT * FROM sbis.sb_members WHERE lname ='" + this.lnametxtbox.Text + "' AND fname = '" + this.fnametxtbox.Text + "' AND mname ='" + this.mnametxtbox.Text + "' ";
MySqlCommand command2 = new MySqlCommand(selectquery, con);
string insertquery = "INSERT INTO sbis.sb_members (lname, fname, mname, position, appointment, address, contactnum, birthdate, civilstatus, educattainment, eligibility, terms_idterms, polparties_id, sex) VALUES (#lname, #fname, #mname, #position, #appointment, #address, #contactnum, #birthdate, #civilstatus, #educattainment, #eligibility, #terms_idterms, #polparties_id, #sex)";
MySqlCommand cmd = new MySqlCommand(insertquery, con);
string lname, fname, mname, address, contactnum, educattainment;
lname = lnametxtbox.Text;
fname = fnametxtbox.Text;
mname = mnametxtbox.Text;
address = addresstxtbox.Text;
contactnum = contacttxtbox.Text;
educattainment = eductxtbox.Text;
var birthdate = birthdatedtp.Value.Date;
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#contactnum", contactnum);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#appointment", appointment);
cmd.Parameters.AddWithValue("#birthdate", birthdate);
cmd.Parameters.AddWithValue("#sex", sex);
cmd.Parameters.AddWithValue("#eligibility", eligibility);
cmd.Parameters.AddWithValue("#civilstatus", civilstatus);
cmd.Parameters.AddWithValue("#terms_idterms", terms);
cmd.Parameters.AddWithValue("#polparties_id", polparties);
cmd.Parameters.AddWithValue("#educattainment", educattainment);
try {
con.Open();
MySqlDataReader cr = command2.ExecuteReader();
while (cr.Read()) {
if (cr.HasRows == true) {
MessageBox.Show("Member already exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
} else if (cr.HasRows == false) {
if (cmd.ExecuteNonQuery() > 0) {
MessageBox.Show("Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
cr.Close();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
You seem to know how to use prepared statements. So it's a mystery why are using string concatenation in your SELECT
string selectquery = "SELECT * FROM sbis.sb_members WHERE lname ='" + this.lnametxtbox.Text + "' AND fname = '" + this.fnametxtbox.Text + "' AND mname ='" + this.mnametxtbox.Text + "' ";
But the good news is that you don't need this SELECT at all. You can just throw it away. And make use of the IGNORE feature in mysql. Or if you want to display that member already exists message, just catch the exception!
using (con = new MySqlConnection(constring))
{
string insertquery = "INSERT INTO sbis.sb_members (lname, fname, mname, position, appointment, address, contactnum, birthdate, civilstatus, educattainment, eligibility, terms_idterms, polparties_id, sex) VALUES (#lname, #fname, #mname, #position, #appointment, #address, #contactnum, #birthdate, #civilstatus, #educattainment, #eligibility, #terms_idterms, #polparties_id, #sex)";
MySqlCommand cmd = new MySqlCommand(insertquery, con);
string lname, fname, mname, address, contactnum, educattainment;
lname = lnametxtbox.Text;
fname = fnametxtbox.Text;
mname = mnametxtbox.Text;
address = addresstxtbox.Text;
contactnum = contacttxtbox.Text;
educattainment = eductxtbox.Text;
var birthdate = birthdatedtp.Value.Date;
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#contactnum", contactnum);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#appointment", appointment);
cmd.Parameters.AddWithValue("#birthdate", birthdate);
cmd.Parameters.AddWithValue("#sex", sex);
cmd.Parameters.AddWithValue("#eligibility", eligibility);
cmd.Parameters.AddWithValue("#civilstatus", civilstatus);
cmd.Parameters.AddWithValue("#terms_idterms", terms);
cmd.Parameters.AddWithValue("#polparties_id", polparties);
cmd.Parameters.AddWithValue("#educattainment", educattainment);
try
{
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
if (ex.Message.ToLower().Contains("duplicate key"))
{
MessageBox.Show("Member already exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else {
MessageBox.Show(ex.Message);
}
}
}
}
The above example catches the duplicate key error to display the message that the user exists rather that ignoring errors.
Of course all this assumes that you have created a UNIQUE or PRIMARY KEY constraint on the column that you do not want duplicated. That's a fundamental part of database design. And the standard practice is to rely on the database to enforce uniqueness and other constraints rather than doing it at the application level
The while (cr.Read()) is the problem, if the (read) table is empty (no duplicate), the loop never runs.
But the approach is bad because You have race conditions. What if someone inserts row after You checked that there is none? To really enforce the constraint, just add
ALTER TABLE sbis.sb_members ADD UNIQUE (lname, fname, mname)
Now You are safe from duplicates.
I am using a GridView, and I followed instructions here: http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx
Now I am getting the error: Procedure or function 'spRegistrantsGridView' expects parameter '#RegistrantId', which was not supplied
This is my StoredProcedure:
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int,
#FirstName nvarchar(20),
#LastName nvarchar(25),
#AddressLine1 nvarchar(50),
#AddressLine2 nvarchar(50),
#City nvarchar(30),
#State nvarchar(2),
#Zip nvarchar(10),
#Country nvarchar(20),
#Phone nvarchar(15),
#PhoneExt nvarchar(4),
#Email nvarchar(50),
#MemberId bigint,
#Comments nvarchar(300)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT RegistrantId,
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
Comments
FROM Registrant
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Registrant(
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
MemberId,
Comments)
VALUES (
#FirstName,
#LastName,
#AddressLine1,
#AddressLine2,
#City,
#State,
#Zip,
#Country,
#Phone,
#PhoneExt,
#Email,
#MemberId,
#Comments)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE Registrant SET
FirstName = #FirstName,
LastName = #LastName,
AddressLine1 = #AddressLine1,
AddressLine2 = #AddressLine2,
City = #City,
State = #State,
Zip = #Zip,
Country = #Country,
Phone = #Phone,
PhoneExt = #PhoneExt,
Email = #Email,
MemberId = #MemberId,
Comments = #Comments
WHERE RegistrantId = #RegistrantId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Registrant
WHERE RegistrantId = #RegistrantId
END
END
And the part of my C# where it throws the error (specifically at sda.Fill(dt);):
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
The parameter #RegistrantId wasn't added when calling the stored procedure.
Add the parameter to your code like so:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
// missing parameter
cmd.Parameters.AddWithValue("#RegistrantId", [insert id]);
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
EDIT
Now your SP is in your question the issue is you have multiple parameters specified but you're only adding one in your c# code. Either remove the params from your SP or make them optional by adding = null
e.g.
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int = null,
#FirstName nvarchar(20) = null,
...
I would like to add into my query name of table from my string variable tablename. Is it possible in c#? I tried something like below. But it doesn't work. As you can see i want to set the FROM #tablename on scores
public void tableInsertTest()
{
MySqlConnection conn = null;
string tablename = "scores";
try
{
conn = new MySqlConnection(cs);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 90;
cmd.CommandText = (
"INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
"SELECT NOW(), name, lname, score FROM #tablename " );
cmd.Prepare();
cmd.Parameters.AddWithValue("#tablename", tablename);
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return;
}
cmd.CommandText = ("INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
string.Format("SELECT NOW(), name, lname, score FROM {0} ", tablename) );
Your query is only a string and you have the value :)
Question: data gets duplicated when inserting into database. How do I not make duplicate entries in database?
I read about securing/ preventing SQL injection by not using the
texboxt1.text
So I tried using
parameters.add()
But the entries are duplicated for every insertion.
This is the image of the database...
This is my code
protected void Button1_Click(object sender, EventArgs e)
{
string username = txtuser.Text;
string firstname = txtfirst.Text;
string lastname = txtlast.Text;
string email = txtemail.Text;
string password = txtpass.Text;
string gender = rbgender.Text;
string nationality = ddcountry.Text;
string Connect_string = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection Connect = new SqlConnection(Connect_string);
Connect.Open();
string pass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
SqlCommand Command = new SqlCommand("INSERT INTO [Users] (username, firstname, lastname, email, password, gender, nationality) VALUES (#username, #firstname, #lastname, #email, #password, #gender, #nationality)", Connect);
Command.Parameters.AddWithValue("#username", username);
Command.Parameters.AddWithValue("#firstname", firstname);
Command.Parameters.AddWithValue("#lastname", lastname);
Command.Parameters.AddWithValue("#email", email);
Command.Parameters.AddWithValue("#password", pass);
Command.Parameters.AddWithValue("#gender", gender);
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
else
{
Label1.Text = "Your information has not been entered to database";
Connect.Close();
}
When I use
INSERT INTO Table () VALUE '"+textbox1.text +"'
it doesn't get duplicated but yeah, SQL injection-thingy.
You have two calls to the ExecuteNonQuery which actually fires the command:
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery(); //CALLED HERE First Time
int success = Command.ExecuteNonQuery(); //CALLED HERE Second Time (This is the one you want)
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
You are executing the query twice, by these lines:
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
Remove the first Command.ExecuteNonQuery() and leave the second one with the int success.