Checking if id and reg already exists - c#

I have this table Profile which has fields with user_Id and regNo and I want to check first if id and email are already exists before proceed to inserting data.
In my code, I am able to validate only one row (either id or reg number), but if I am going to validate the two of them, it gives me an error, saying "Must declare the scalar variable #userid". I don't know if it is with my select that is wrong or something in my code.
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con);
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
//cmdd.Parameters.Add(param1);
SqlDataReader reader = cmdd.ExecuteReader();
if (reader.HasRows)
{
MessageBox("User Id/Registry Number already exists");
}
else
{
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
SqlCommand cmd = new SqlCommand("qry", con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#regno", txtregNo.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
MessageBox("successfully saved!");
}
I am using C# with asp.net.

OK, so this isn't going to work:
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
because you're reassigning the value of the same object. Change that to this:
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
this will add the parameters, two of them, to the SqlCommand object. Now, a little more advice, consider doing this:
using (SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"))
{
con.Open();
using (SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con))
{
...
using (SqlDataReader reader = cmdd.ExecuteReader())
{
...
}
}
}
because right now you're not disposing those object properly.
You see, anything that implements IDisposable should be wrapped in a using statement to ensure the Dispose method is called on it.

param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
You are only declaring 1 parameter and overwriting it for both ParameterName and Value.
As an aside, you should consider looking into some type of data access helper or ORM or something to save you the trouble of all that boilerplate SQL connection code.
You are also opening another connection inside of what should already be an open SQL connection.

You are using one instance of sql parameter and passing it two different values thus overriding the first one. Try it like this:
SqlParameter param1 = new SqlParameter("#userid", txtid.Text);
SqlParameter param2 = new SqlParameter("#reg", txtregNo.Text);

Your problem as per the error is that you are reassigning the parameter to #reg after you assign it to #userid.
Try this:
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select user_id from Profile where user_Id = #userid AND RegNo = #reg", con);
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
var id = cmdd.ExecuteReader() as string;
if (String.IsNullOrEmpty(id))
{
//Show error message and exit the method
}
else
{
//Add the row to the database if it didn't exist
}
EDIT:
I added some code to show how you could check if the userId exists in the table. Then you check against the user id itself instead of checking a reader object. Note, i am not at my dev computer right now so I did not compile this, you may have to do some tweaks but the idea is there.

Related

C# Npgsql read cursor from procedure output parameter

I'm migration an application from a Oracle DB to a Postgres DB.
There are many procedures implemented that returns via output parameter a RefCursor. Just like this:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
OracleConnection conn = GetConnection(connStr);
OracleCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", OracleDbType.Varchar2, ParameterDirection.Input).Value = flowKey;
OracleParameter outCursor = cmd.Parameters.Add("p_cursor", OracleDbType.RefCursor, ParameterDirection.Output);
cmd.ExecuteNonQuery();
OracleRefCursor dataCursor = (OracleRefCursor)outCursor.Value;
OracleDataAdapter myAdapter = new OracleDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
Please notice thant I've to grab the parameter outCursor, cast as OracleRefCursor and set it to DataTable named "tableData" via DataAdapter.
To do the same but using Npgsql this is my approach:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", NpgsqlDbType.Varchar).Value = flowKey;
NpgsqlParameter outCursor = cmd.Parameters.Add(new NpgsqlParameter("p_cursor", NpgsqlDbType.Refcursor) { Direction = ParameterDirection.Output });
cmd.ExecuteNonQuery();
var dataCursor = (Refcursor)outCursor.Value;
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
But unfortunately seems that there is no equivalent in Npgsql for Refcursor
Any ideias how can I get arround this?
Thank you.
To everyone who needs to do the same, I recommend reading this: https://stackoverflow.com/a/47970680/2229993
Nonetheless this is how I solved this issue:
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = new NpgsqlCommand("CALL show_citiesProc('op');FETCH ALL IN \"op\";", conn);
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter(cmd);
myAdapter.Fill(tableData);
myAdapter.Dispose();

Get value of key with dynamic where clause in Appsettings

I want to get the value of key with dynamic where clause in appSettings portion in web.config project (ASP.NET and C#) like this:
key="test" value="Select * from table where id=Textbox1.Text"
How can I achieve this?
You can do it like this:
// Get sql query and add where clause to it.
string sqlString = System.Configuration.ConfigurationManager.AppSettings["test"] + " where id=#id";
// Execute sqlString
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlParameter param = new SqlParameter();
param.ParameterName = "#id";
param.Value = Textbox1.Text;
cmd.Parameters.Add(param);
SqlDataReader reader;
cmd.CommandText = sqlString;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Edit
C# for prevent SQL injection, stop executing commands that do this. You should use SqlParameter.

Update table record from sqlcommand

I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}

How do I code a login page in C# while verifying login details in SQL Database?

Ok, I am at wits end. I have a login page for teachers. The Username which is the teacher ID(integer) and the password(string) have to match what's already in the Teachers table that I've got in SQL. Please be aware that my knowledge and understanding is very basic. This is part of an assignment for C# module in SD Diploma. Obviously my code so far is not working. What an I doing wrong? My code is below....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace School_System_Project
{
public partial class Login2 : Form
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
public Login2()
{
InitializeComponent();
}
private void btnTLogin_Click(object sender, EventArgs e)
{
string msg = "Teacher ID or Password cannot be left blank!";
if (txtTID.Text == "")
{
lblMessage1.Text = msg;
return;
}
if (txtTPW.Text == "")
{
lblMessage1.Text = msg;
return;
}
conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["Name of connection string"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT TID, Password FROM Teacher WHERE TID = #ID
AND Password = #Password";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#ID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = txtTID.Text;
command.Parameters.Add(param).Value = Int32.Parse(txtTID.Text);
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Password";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = txtTPW.Text;
command.Parameters.Add(param2);
adapter.SelectCommand = command;
adapter.SelectCommand.ExecuteReader();
SqlDataReader reader = command.ExecuteReader();
if (txtTID.Text == param.ParameterName && txtTPW.Text == param2.ParameterName)
{
MainTeachers mainteachers = new MainTeachers();
mainteachers.ShowDialog();
}
else
{
lblMessage1.Text = "Incorrect login details, please try again";
}
reader.Dispose();
command.Dispose();
conn.Dispose();
}
OK - lots of stuff to clear up...
SqlParameter param = new SqlParameter();
param.ParameterName = "#ID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = txtTID.Text;
command.Parameters.Add(param).Value = Int32.Parse(txtTID.Text);
Why are you setting the value twice? First you set it to what looks like a string (but the parameter is defined as SqlDbType.Int, and then you add the parameter and set its value again - this time to an int. Which one of those assignments do you want to keep??
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Password";
param.SqlDbType = SqlDbType.Int;
From here on out, you're using param., while the parameter you're defining is really param2 - copy&paste error??? Needs to be fixed!
Also: is the password parameter really of type SqlDbType.Int??? .....
Please tell me you're not really storing all those passwords in clear text in your database! That would be a MAJOR no-no and gaping security issue in your system!
Also: you execute your reader - but you're never really reading any data from it.....
I would rewrite your code to something like this to take advantage of all the usual best practices working with ADO.NET and raw SQL:
// define the query you want to execute
string query = "SELECT TID, Password FROM Teacher WHERE TID = #ID AND Password = #Password";
// establish connection and command objects, both wrapped into using(){} blocks to
// ensure proper disposal, even in case of an exception
using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Name of connection string"].ConnectionString))
using (SqlCommand command = new SqlCommand(query, conn))
{
// add paramters and set values
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(txtTID.Text);
command.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = txtTPW.Text;
// open connection
conn.Open();
// execute your reader
using (SqlDataReader reader = command.ExecuteReader())
{
// you need to actually *read* from the reader here! What are you trying to do?
// just check if that row with ID and password exist? Fetch some data?
bool idExists = reader.HasRows();
reader.Close();
}
conn.Close();
}
Except for the error pointed out by Rahul Singh.
The data that you want is inside your SqlDataReader reader variable. param.ParameterName will always be "#ID"
Try logging in with the user = #ID and password= #Password and you will be redirected to the form.

how to fetch data using this coding

using this coding,while i give fruitId ,i need to retrieve fruitname,using this it shows some error..any one help...
string constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("savefruit11", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitsId", int.Parse(TextBox3.Text.Trim()));
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
}
}
Store procedure for the above code.
use[FruitsDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[savefruit11]
#FruitId INT,
#FruitName VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #FruitName = Fruitsname
FROM Fruits1
WHERE FruitsId = #FruitId
END
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
Your parameter is called #Fruitsname, but you get it back with #FruitName. You have an additional s in the first version. Make them consistent by changing the first #FruitsName to #FruitName which will match what you have in the stored procedure.
Or, as Henk suggested in the comments create a const string to contain your parameter name so that it is consistent across all usages.
Use cmd.ExecuteQuery or cmd.ExecuteScalar
//To Execute SELECT Statement
ExecuteQuery()
//To Execute Other Than Select Statement(means to Execute INSERT/UPDATE/DELETE)
ExecuteNonQuery()
with your udpate
s is missing in parameter name in stored procedure
Use the following example way
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.AdventureWorksData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = "HumanResources.uspUpdateEmployeePersonalInfo";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(
new SqlParameter("#EmployeeID", entity.EmployeeID));
command.Parameters.Add(
new SqlParameter("#NationalIDNumber", entity.NationalIDNumber));
command.Parameters.Add(
new SqlParameter("#BirthDate", entity.BirthDate));
command.Parameters.Add(
new SqlParameter("#MaritalStatus", entity.MaritalStatus));
command.Parameters.Add(
new SqlParameter("#Gender", entity.Gender));
connection.Open();
command.ExecuteNonQuery();
}
}
reference from MSDN
http://msdn.microsoft.com/en-us/library/jj635144.aspx

Categories