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
}
Related
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();
}
}
}
I have a table with 1 record and I made a stored procedure for it to use in my button click, but it's letting me pass any values and when I test it in sql, it works as expected. Just wondering if any of you can point out the bug in my code.
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataReader dr = default(SqlDataReader);
SqlCommand cmd = default(SqlCommand);
string userName = txtUserName.Text;
string password = txtPassword.Text;
using (SqlConnection conn = new SqlConnection(strConn))
{
cmd = new SqlCommand("adminAuthentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", userName);
cmd.Parameters.AddWithValue("#Password", password);
conn.Open();
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
lblMessage.Text = "Successfull login!";
}
else
{
lblMessage.Text = "Wrong user/password";
conn.Close();
}
}
}
Stored procedure:
CREATE PROC adminAuthentication
(
#UserName varchar(15),
#Password varchar(25)
)
AS
BEGIN
SELECT COUNT(1)
FROM AdminLogin
WHERE UserName = #UserName AND Pwd = #Password
END
I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.
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();
}
I'm inserting data in two tables at once...
CREATE PROCEDURE inserttwo
(
#BookID int,
#BookName nvarchar(50),
#DateIssue datetime,
#ReturnDate datetime,
#PersonID int
)
AS
INSERT INTO tblReturn(BookID, BookName, DateIssue, ReturnDate, PersonID)
VALUES(#BookID, #BookName, #DateIssue, #ReturnDate, #PersonID)
INSERT INTO tblIssue(BookID, BookName, DateIssue, ReturnDate, PersonID)
VALUES(#BookID, #BookName, #DateIssue, #ReturnDate, #PersonID)
then I'm updating and deleting these tables by stored procedure...
Delete query:
ALTER PROCEDURE [dbo].[Issuedelete]
(#BookID int)
AS
DELETE FROM tblIssue
WHERE BookID = #BookID
Update query:
ALTER PROCEDURE [dbo].[IssueUpdate]
(#BookID int,
#BookName nvarchar(50),
#DateIssue datetime,
#ReturnDate datetime,
#PersonID int)
AS
UPDATE tblIssue
SET [BookID] = #BookID ,
[BookName] = #BookName,
[DateIssue] = #DateIssue,
[ReturnDate] = #ReturnDate,
[PersonID] = #PersonID
WHERE BookID = #BookID
C# code to delete from tblIssue:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("Issuedelete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BookID", ComBox1BookID.Text);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
C# code to update tblIssue:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BookID", ComBox1BookID.Text);
cmd.Parameters.AddWithValue("#BookName", ComBox2BName.Text);
cmd.Parameters.AddWithValue("#DateIssue", IssueDate.Value.ToString());
cmd.Parameters.AddWithValue("#ReturnDate", ReturnDate.Value.ToString());
cmd.Parameters.AddWithValue("#PersonID", CBox3PerID.Text);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
After compiling, I get an error
Can't convert datatype into int
I tried other ways by changing the parameters with OleDB and SqlDbType... But it's not deleting and updating records... And also having same problem when I'm updating and deleting into tblReturn... Please, help me??? :(
You are sending text values to integer and datetime parameters, Change your update button click event code to
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BookID", Convert.ToInt32(ComBox1BookID.Text));
cmd.Parameters.AddWithValue("#BookName", ComBox2BName.Text);
cmd.Parameters.AddWithValue("#DateIssue", IssueDate.Value);
cmd.Parameters.AddWithValue("#ReturnDate", ReturnDate.Value);
cmd.Parameters.AddWithValue("#PersonID",Convert.ToInt32(CBox3PerID.Text));
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
Update
Remove this line after set in your update stored procedure
[BookID] =#BookID ,
if its a identity column, it will throw exception on updating it.
Update 2
Try this cmd.Parameters.Add("#BookID", SqlDbType.Int).Value = Convert.ToInt32(ComBox1BookID.Text);
if you are adding parameters with add function