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.
Related
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();
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
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.
I'm developing an application in C# that connects to an Oracle 10g database.
I'm using Oledb like this:
OleDbConnection conn = ConnectionUtil.CreateConexion();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = SP_AUTENTICAR_USUARIO;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_SED_USUARIO", OleDbType.VarChar).Value = strUsuario;
cmd.Parameters.Add("p_SED_PASS", OleDbType.VarChar).Value = strPass;
cmd.Parameters.Add("p_cursor", OleDbType.Cursor).Direction = ParameterDirection.Output;//I dont know what to put here
conn.Open();
cmd.ExecuteNonQuery();
OleDbDataReader objReader = (OleDbDataReader)cmd.Parameters["p_cursor"].Value;
if (objReader.Read())
{...
I need to call a stored procedure and read a cursor with OleDbDataReader.
Any idea how to do that?
Thanks,
Please Check this sample code.this is using OracleDataReader
oraConn.Open();
OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn);
cursCmd.CommandType = CommandType.StoredProcedure;
cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataReader rdr = cursCmd.ExecuteReader();
Console.WriteLine("\nEmp ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}, {2}", rdr.GetOracleNumber(0), rdr.GetString(1), rdr.GetString(2));
rdr.NextResult();
Console.WriteLine("\nDept ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}", rdr.GetOracleNumber(0), rdr.GetString(1));
rdr.Close();
oraConn.Close();
I've not used basic SQL commands for a while and I'm trying to pass a param to a sproc and the run it. However when I run the code I get a "Not Supplied" error.
Code:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.Parameters.Add(new SqlParameter("#ID", itemId));
conn1.Open();
cmd1.ExecuteNonQuery();
I'm not really sure why this would fail. Apologies for the basic question, but I'm lost!
Thanks in advance.
You should set the CommandType to StoredProcedure, set the connection and use Parameters.AddWithValue("#ID", itemID)
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Connection = conn1;
cmd1.Parameters.AddWithValue("#ID",itemID);
conn1.Open();
cmd1.ExecuteNonQuery();
If you want to use Parameters.Add() (which is obsolete), here is how you do it (you need to pass the type too)
cmd1.Parameters.Add("#ID", SqlDbType.Int); //string maybe, I don't know
cmd1.Parameters["#ID"].Value = itemID;
This should work:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
And to make your code even better, put your SqlConnection and SqlCommand into using statements, so that they'll be freed automatically at the end of the using block:
using(SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr()))
{
using(SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
}