Sequential stored procedure with User Input - c#

I have a web app that takes user input and generates an image from user input. Those images should be generated in a sequence and will need to reset everyday.
I'm trying to at least store the sequence values, the sequence and the date into a database, but it will not update.
So far, my database will not update, my code works, but is not performing correctly. I'm not sure where my problem lies. I found similar help online, but they did not seem to work.
Stored procedure:
ALTER PROCEDURE barcode_insert(
#Seq_Num int,
#date datetime,
#ImageName varchar
)
AS
BEGIN
SET NOCOUNT ON
UPDATE ImageInfoTable
SET imagedate = #date,ImageNum = #Seq_Num
WHERE image_name = #ImageName
END
RETURN #Seq_Num
C# Code
protected void gen_barcode(object sender, EventArgs e)
{
int n;
int i = Int32.Parse(amount.Text);
string date_picker = datepicker.Text;
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "barcode_insert"
cmd.Parameters.AddWithValue("#Seq_Num", amount.Text);
cmd.Parameters.AddWithValue("#date", date_picker);
cmd.Parameters.AddWithValue("#ImageName", CheckBox.Checked);
if (CheckBox_Code.Checked)
{
//generate image code
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Try setting the types of your parameters explicitly.
protected void gen_barcode(object sender, EventArgs e)
{
DateTime date_picker = datepicker.Value;
int intAmount; // get the int value for the amount here...
String imgName; // get the image name here...
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "barcode_insert"
cmd.Parameters.Add("#Seq_Num", SqlDbType.Int);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
cmd.Parameters.Add("#ImageName" , SqlDbType.NVarChar);
cmd.Parameters["#Seq_Num"].Value = intAmount;
cmd.Parameters["#date"].Value = date_picker;
cmd.Parameters["#ImageName"].Value = imgName;
if (CheckBox_Code.Checked)
{
//put this somewhere else since it isn't related in function
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Related

Trying to add a C# variable into a row in an existing table using windows form [duplicate]

I'm able to delete, insert and update in my program and I try to do an insert by calling a created stored procedure from my database.
This button insert I made works well.
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (#FirstName, #LastName)", con);
da.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
This is the start of the button that calls the procedure named sp_Add_contact to add a contact. The two parameters for sp_Add_contact(#FirstName,#LastName). I searched on google for some good examples but found nothing interesting.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
cmd.CommandType = CommandType.StoredProcedure;
???
con.Open();
da. ???.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.
Also, use a using for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("#LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
cmd.Parameters.Add(String parameterName, Object value) is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they
deprecated the cmd.Parameters.Add(String parameterName, Object value) in favor of AddWithValue(String parameterName, Object value) is to give more
clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
public void myfunction(){
try
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlcon.Close();
}
}
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
#COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = #COUNTRY
GO
The above stored procedure is accepting a country name (#COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money
public void SaveTransaction(Transaction transaction)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (var cmd = new SqlCommand("spAddTransaction", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
cmd.Parameters.AddWithValue("#" + prop.Name, prop.GetValue(transaction, null));
con.Open();
cmd.ExecuteNonQuery();
}
}
}

Call multiple stored procedure to the 2 different gridview in ASP.NET

I have two stored procedures:
spRO_Status_OrderInfo
spRO_Status_Change
Each procedure returns a different table. I have only one user input parameter TN. This parameter I'm reading from search txt line (inputTNReturn.Value)
Each procedure posts data in a different grid view
spRO_Status_OrderInfo -->> gvSearchResults
spRO_Status_Change -->> GridView1
This code returns only LAST stored procedure to last gridView
spRO_Status_Change -->> GridView1
I don't have any idea where is my mistake and why I can get 2 grid view from 2 procedure.
I'll appreciate for any help
protected void btnSearch_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
if (inputTNReturn.Value.Trim() != "")
{
SqlParameter param = new SqlParameter("#TN", inputTNReturn.Value);
cmd.Parameters.Add(param);
SqlDataReader rdr = cmd.ExecuteReader();
gvSearchResults.DataSource = rdr;
gvSearchResults.DataBind();
GridView1.DataSource = rdr;
GridView1.DataBind();
lblinputTNReturn.Text = inputTNReturn.Value;
}
}
if (inputTNReturn.Value == "")
{
inputTNReturn.Value = "Please add tracking number";
}
con.Close();
}
}
Here is where you're setting the first stored procedure
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
Here is where you're overwriting the above
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
You're not adding a second command text / type, you're just over writing the first one which is why you're only seeing the second one come out in the output.

Calling an Oracle Stored Procedure in C#

I am trying to call an Oracle stored procedure from a C# program. I am using a SYS_REFCURSOR an the output of the stored procedure. I am getting invalid SQL error when I reach the line
OracleDataReader reader = cmd.ExecuteReader()
in my C# program. I can't figure out why I am getting this invalid SQL error.
Here is the C# code:
private void button1_Click(object sender, EventArgs e)
{
string custname;
int custnbr;
List<Customer> customers = new List<Customer>();
string oradb = "User Id=XXXXX;Password=XXXXX;Data Source=IP:PORT/xxxx;Pooling=false;";
OracleConnection conn = new OracleConnection(oradb);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROCEDURE_TEST";
OracleParameter oraP = new OracleParameter();
oraP.ParameterName = "R_RECORDSET";
oraP.OracleDbType = OracleDbType.RefCursor;
oraP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(oraP);
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
custnbr = reader.GetInt32(0);
custname = reader.GetString(1);
Customer custTemp = new Customer(custnbr, custname);
customers.Add(custTemp);
}
foreach (var cust in customers)
{
textBox1.AppendText("Customer Number: " + cust.custnbr + "\t");
textBox1.AppendText("Customer Name: " + cust.custname + "\r\n");
}
}
catch(Exception ex)
{
textBox1.AppendText(ex.ToString());
conn.Close();
}
}
Here is the Oracle stored procedure:
create or replace PROCEDURE PROCEDURE_TEST
( R_RECORDSET OUT SYS_REFCURSOR) AS
BEGIN
OPEN R_RECORDSET FOR
SELECT POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT, SUM(POTCHARGEQTY), SUM(POTCHARGEAMOUNT)
FROM riowner.ccum_customer customer
WHERE ic.collection_Datetime =
TO_DATE('30-SEP-2015 23:59:59','DD-MON-YYYY HH24:MI:SS')
GROUP BY POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT;
END PROCEDURE_TEST;
cmd.CommandType = CommandType.Text;
should be
cmd.CommandType = CommandType.StoredProcedure;
As an alternative to MethodMan's answer, you should be able to keep the command type as Text, but change your SQL command to this:
cmd.CommandText = "BEGIN PROCEDURE_TEST END;";
MethodMan's method is better if you just need to call one procedure, but the way I did it above would allow you to do more procedures, so it's something to be aware of in the future.

The name '"' does not exist in the current context

I am facing several errors in my code. These errors are:
Error 17 The name 'CommandType' does not exist in the current context
Error 18 The name 'SqlDbType' does not exist in the current context
Error 35 The name 'txtCity' does not exist in the current context
I would like if you can help me to understand the error and tell me how I can fix it.
protected void btnSave_Click(object sender, EventArgs e)
{
// create connectionstring and insert statment
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string insertSql = " INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email, Country,State, City)" +
" values (#UsrNme, #fnbox, #lnamebox, #passtxtbx1, #passtxtbx2, #emailbox, #DrDncoundrlst, #DropDownListSwestate, #citytxtbox)";
// create SQL Connection
SqlConnection con = new SqlConnection(connectionString);
// create sql command and parameters
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.text;
cmd.CommandText = insertSql;
SqlParameter UID = new SqlParameter("#UsrNme", SqlDbType.nvarchar, 50);
UID.Value = txtUID.text.tostring();
cmd.Parameters.Add(UID);
SqlParameter FN = new SqlParameter("#fnbox", SqlDbType.varchar,25);
cmd.Connection = con;
FN.Value = txtfn.text.ToString();
cmd.Parameters.Add(FN);
SqlParameter LN = new SqlParameter("#lnamebox", SqlDbType.varchar, 25);
cmd.Connection = con;
LN.Value = txtLN.text.ToString();
cmd.Parameters.Add(LN);
SqlParameter Password = new SqlParameter("#passtxtbx1", SqlDbType.varchar, 25);
cmd.Connection = con;
Password.Value = txtPassword.text.ToString();
cmd.Parameters.Add(Password);
SqlParameter RePass = new SqlParameter("#passtxtbx2", SqlDbType.varchar, 25);
cmd.Connection = con;
RePass.Value = txtRePass.text.ToString();
cmd.Parameters.Add(RePass);
SqlParameter Email = new SqlParameter("#emailbox", SqlDbType.varchar, 25);
cmd.Connection = con;
Email.Value = txtEmail.text.ToString();
cmd.Parameters.Add(Email);
SqlParameter Country = new SqlParameter("#DrDncoundrlst", SqlDbType.varchar, 25);
cmd.Connection = con;
Country.Value = txtCountry.text.ToString();
cmd.Parameters.Add(Country);
SqlParameter State = new SqlParameter("#DropDownListSwestate", SqlDbType.varchar, 25);
cmd.Connection = con;
State.Value = txtState.text.ToString();
cmd.Parameters.Add(State);
SqlParameter City = new SqlParameter("#citytxtbox", SqlDbType.varchar, 25);
cmd.Connection = con;
City.Value = txtCity.text.ToString();
cmd.Parameters.Add(City);
try
{
con.Open();
cmd.ExecuteNonQuery();
lblmsg.Text = "You already complete your registration process";
}
catch (SqlException ex)
{
string errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
}
You may be way over-complicating things. Try the following code...
var connection = new SqlConnection(connectionString);
var cmd = new SqlCommand(insertSql, connection);
cmd.Parameters.AddWithValue("#UsrNme", txtUID.Text.ToString());
cmd.Parameters.AddWithValue("#fnbox", txtfn.Text.ToString());
cmd.Parameters.AddWithValue("#lnamebox", txtLN.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx2", txtRePass.Text.ToString());
cmd.Parameters.AddWithValue("#emailbox", txtEmail.Text.ToString());
cmd.Parameters.AddWithValue("#DrDncoundrlst", txtCountry.Text.ToString());
cmd.Parameters.AddWithValue("#DropDownListSwestate", txtState.Text.ToString());
cmd.Parameters.AddWithValue("#citytxtbox", txtCity.Text.ToString());
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
lblmsg.Text = "You already completed your registration process";
}
catch (SqlException ex)
{
var errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
You also want to make sure the you have the following using clauses declared...
using System.Data;
using System.Data.SqlClient;
... and that txtCity is what you actually called your text box and that it's not hidden from this method by a private identifier or actually appears on a different form because the error you're getting means that the variable is outside the method's scope or has its lifetime expire before you reach this method.
Here's what all that code does. Instead of setting up tons of metadata that you should not need to declare your parameters, it lets SqlCommand do all the hard work for you and figure out what type is what based on the database column, the type of the object you passed in, and the name of the parameter. If you end up allowing the passing of invalid data, none of the elaborate metadata markup is going to save you from an error.
Likewise, you really want to look into wrapping your insertSql into a stored procedure like so in Sql Server...
create procedure adduserinfo #UsrNme nvarchar (50),
#fnbox varchar (25),
#lnamebox varchar (25),
#passtxtbx1 varchar (25),
#passtxtbx2 varchar (25),
#emailbox varchar (25),
#DrDncoundrlst varchar (25),
#DropDownListSwestate varchar (25),
#citytxtbox varchar (25)
as begin
INSERT INTO UserInfo
( UID,
FN,
LN,
Password,
RePass,
Email,
Country,
State,
City )
VALUES
( #UsrNme,
#fnbox,
#lnamebox,
#passtxtbx1,
#passtxtbx2,
#emailbox,
#DrDncoundrlst,
#DropDownListSwestate,
#citytxtbox )
end
go
Then your SqlCommand declaration would look like so...
var command = new SqlCommand("adduserinfo", connection)
{
CommandType = CommandType.StoredProcedure;
}
... and for the rest you'd follow the rest of the code I provided above. This would be the more or less proper way to do it. And at the risk of sounding nitpicky, consider more informative and consistently formatted variable and parameter names. Those who might have to modify your code in the future will thank you for it.

SQL Server error: ExecuteNonQuery: Connection property has not been initialized

I am trying to develop a sample registration page using ASP.Net and C#. I am calling a stored procedure to insert the data to database. My database is SQL Server 2008.
This is my code:
public partial class Sample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
string str;
protected void Page_Load(object sender, EventArgs e)
{
rbt_Male.Checked = true;
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
string #Name = txtbx_Name.Text;
string #Gender_male = rbt_Male.Text;
string #Gender_Female = rbt_Female.Text;
string #Email = txtbx_Email.Text;
DateTime #Dob = Convert.ToDateTime(txt_Dob.Text);
submitdata();
}
protected void submitdata()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
if (rbt_Male.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Male", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
else if (rbt_Female.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Female", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = "Record Inserted Successfully";
con.Close();
}
catch (Exception ex)
{
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = ex.Message;
}
I am getting the error message
ExecuteNonQuery: Connection property has not been initialized.
I am getting this error at cmd.ExecuteNonQuery();
Please help me.
My stored procedure is
ALTER Procedure insertdata
(
#Name Varchar(20),
#Gender Varchar(6),
#Email Varchar(20),
#Dob date
)
As
Begin
Insert into samplelogintable (Name, Gender, Email, Dob)
Values(#Name, #Gender, #Email, #Dob)
End
You haven't associated your command cmd with your SqlConnection, that is why you are getting the error.
You need to specify:
cmd.Connection = con;
in your submitdata() method.
Since SqlCommand implements IDisposable, its better if you use it within using block like:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code
}

Categories

Resources