public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}
/*
* There are 2 c# objects i have shown
* There is a stored procedure in my application which
* returns data for both objects simultaneously
* eg
* select FirstName, LasteName from Users where something="xyz"
* select City,Country from Locations where something="xyz"
*
* both queries are run by single procedure
* Now how can i fill both objects with from that stored procedure in asp.net using c#
*/
Use ADO.NET, open a SqlDataReader on a SqlCommand object executing the SP with the parameters. Use the SqlDataReader.NextResult method to get the second result set.
Basically:
SqlConnection cn = new SqlConnection("<ConnectionString>");
cn.Open();
SqlCommand Cmd = new SqlCommand("<StoredProcedureName>", cn);
Cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
while ( dr.Read() ) {
// populate your first object
}
dr.NextResult();
while ( dr.Read() ) {
// populate your second object
}
dr.Close();
You could use ADO.net and design a dataset which will create the classes for you so your queries will execute and read into classes which store the data you got.
http://msdn.microsoft.com/en-us/library/aa581776.aspx
That is an excellent tutorial on how to create a data access layer, which is what it sounds like you want to do.
using(SqlConnection connexion = new Sqlconnection(youconenctionstring))
using(SqlCommand command = conenxion.Createcommand())
{
command.Commandtext = "yourProcName";
command.CommandType = CommandType.StoredProcedure;
command.Paramters.Add("#yourparam",yourparamvalue);
connexion.Open();
SqlDataReader reader = command.ExecuteReader();
List<User> users = new List<User>;
List<Adress> adresses = new List<User>;
while(read.Read())
{
User user = new User();
user.firstName = (string) read["FirstName"];
users.Add(user);
}
read.NextResult();
while(read.Read)
{
Address address = new Address();
address.City = (string) read["Name"];
adresses.Add(address);
}
//make what you want with your both list
}
Linq to SQL, Entity Framework, or NHibernate would be my suggestions.
Check out the Enterprise library, specifically the Data Access block from microsoft patterns and practices. Even if you don't use it, you can steal, er... borrow code from it to do what you want.
http://www.codeplex.com/entlib
Related
I have a permissions database that I created which has 10 data points in it. I can insert data into this table through the program, but when I try to pull the data it's been giving me a lot of headaches. I've attempted to use a Using loop and it errors out every time, so I'm trying to just go super basic, and pull the data line by line but it's not working at all. My goal is to pull all the data into a List Variable so that I can call each individual permission later. What is stored in each permission is simply the Text True or False, with the exception of the first one Emp_ID being an Int.
Con is my connection script, and it's working perfectly, as it works everywhere else within the program.
Settings.Emp_ID is the Emp_ID of the user that's currently logged in. This means that we can skip the Emp_ID from the permissions when pulling the data, but I've attempted to do an EXCLUDE or SKIP but it's failed every time as well.
SQL Format, Emp_ID = INT, all others = Text
As for Error:
System.NullReference Exception 'Object Reference Not set to an instance of an object.
namespace TMS
{
public partial class Login_Form : Form
{
string[] Data;
void verify()
{
SqlDataReader rdr = null;
SqlCommand cmd = new SqlCommand("SELECT * FROM Permissions WHERE Emp_ID = '"
+ Settings.Emp_ID + "'", Con);
try
{
Con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int Emp_ID = (int)rdr["Emp_ID"];
Data[0] = (string)rdr["Check_Out"];
Data[1] = (string)rdr["Check_In"];
Data[2] = (string)rdr["Self_His_Tool"];
Data[3] = (string)rdr["Self_His_User"];
Data[4] = (string)rdr["Tool_His"];
Data[5] = (string)rdr["User_His"];
Data[6] = (string)rdr["Add_Users"];
Data[7] = (string)rdr["Add_Tools"];
Data[8] = (string)rdr["Remove_Users"];
Data[9] = (string)rdr["Remove_Tools"];
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Con != null)
Con.Close();
}
}
The Data array is still null, because this line does not actually create an array object:
string[] Data;
All it does is create a variable that might someday refer to an array object.
Later, when you have this and lines like it:
Data[0] = (string)rdr["Check_Out"];
You end up with the NullReferenceException. Data is still null, and so trying to access Data[0] is not allowed.
We want something more like this:
public class Permissions
{
//probably these should be "bool", but I adapted the types from the old code
public string Check_Out {get;set;}
public string Check_In {get;set;}
public string Self_His_Tool {get;set;}
public string Self_His_User {get;set;}
public string Tool_His {get;set;}
public string User_His {get;set;}
public string Add_Users {get;set;}
public string Add_Tools {get;set;}
public string Remove_Users {get;set;}
public string Remove_Tools {get;set;}
}
// ...
Permissions Data;
Permissions verify()
{
string SQL = "SELECT * FROM Permissions WHERE Emp_ID = #Emp_ID";
// Do NOT re-use the some connection object throughout an app or class!
// Only re-use the connection string.
// using directive will ensure connection is closed, so no need for finally block
using var con = new SqlConnection("connection string here");
using var cmd = new SqlCommand(SQL, con);
// Do NOT use string concatation to substitute data into a query!
cmd.Parameters.Add("#Emp_ID", SqlDbType.Int).Value = Settings.Emp_ID;
// don't need a "try" if there's no catch or finally
con.Open();
rdr = cmd.ExecuteReader();
Permissions result = null;
if (rdr.Read()) //Don't need "while" if we only expect one record
{
result = new Permissions();
int Emp_ID = Settings.Emp_ID;
result.Check_out =(string)rdr["Check_Out"];
result.Check_In = (string)rdr["Check_In"];
result.Self_His_Tool = (string)rdr["Self_His_Tool"];
result.Self_His_User = (string)rdr["Self_His_User"];
result.Tool_His = (string)rdr["Tool_His"];
result.User_His = (string)rdr["User_His"];
result.Add_Users = (string)rdr["Add_Users"];
result.Add_Tools = (string)rdr["Add_Tools"];
result.Remove_Users = (string)rdr["Remove_Users"];
result.Remove_Tools = (string)rdr["Remove_Tools"];
}
return result;
}
I need to know how I can get the values returned by multiple rows and multiple columns of a query using SqlDataReader in C#.
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
connection.Open();
string query = ("select cardname,cardnumber,expiry,cardballance from vwallet where username='" + uname + "'");
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//cardname = reader[0].ToString();
//cardnumber = reader[1].ToString();
//expiry = reader[2].ToString();
//cardballance = reader[3].ToString();
reader.
}
}
Note: I want to display the result returned by the query i.e cardnames, cardnumbers, expiry and cardballance into labels.
My current understanding is that the code I wrote will read only one row's column and assign to variables (declared already in the code, not pasted declaration here).
Data returned through table:
I want to display all of these in labels.
How to read all the data returned from table (table data shown in picture).
You are almost there. You just need an array or collection to store the rows in.
public class MyCard
{
public string Name { get; set; }
public string Number { get; set; }
public string Expiry { get; set; }
public string Balance { get; set; }
//Please note: This needs updating to match the data type used in your DB table.
//I have used string to show you a simple example.
}
Then update your code to include:
SqlDataReader reader = cmd.ExecuteReader();
List<MyCard> MyCardList = new List<MyCard>();
while (reader.Read())
{
MyCard mycard = new MyCard();
mycard.Name = reader[0].ToString();
mycard.Number = reader[1].ToString();
mycard.Expiry = reader[2].ToString();
mycard.Balance = reader[3].ToString();
MyCardList.Add(mycard);
}
//Remember to close the reader and dispose of objects correctly.
Then you have a list of MyCard objects with all your data.
Is the code below implementing the secure way to retrieve the data from database?
help me please, I don't understand about SQL Injection. Someone told me this code can easily get injected. If yes, can somebody explain it? Thank you.
public int CheckID(string column, string table, string wheres)
{
int i = 0;
sqlcon = ConnectToMain();
string sqlquery = "SELECT "+column+" FROM "+table+" "+wheres+"";
using (sqlcon)
{
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand(sqlquery, sqlcon);
using (sqlcom)
{
SqlDataReader dr = sqlcom.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
i = dr.GetInt32(0);
}
else
{
i = 0;
}
}
sqlcon.Close();
}
return i;
}
This code has far too many problems.
Table, column and criteria are passed as strings and concatenated, which means that the code is prone to SQL injection.
Database details like table, column criteria are spilled into the function's caller. Are you going to use this method to query anything other than a Visitor table?
A reader is used when only a single value is wanted.
The connection is created outside the using block and stored in a field.
This is definitelly a memory leak and probably a connection leak as well. Just create the connection locally.
A simple command call fixes all of these problems:
public int CheckIDVisitor(visitorName)
{
string query = "SELECT ID FROM Visitors where Name=#name";
using (var sqlConn=new SqlConnection(Properties.Default.MyDbConnectionString))
using( var cmd=new SqlCommand(query,sqlConn))
{
var cmdParam=cmd.Parameters.Add("#name",SqlDbType.NVarChar,20);
cmdParam.Value=visitorName;
sqlConn.Open();
var result=(int?)cmd.ExecuteScalar();
return result??0;
}
}
You could also create the command in advance and store it in a field. You can attach the connection to the command each time you want to execute it:
public void InitVisitorCommand()
{
string query = "SELECT ID FROM Visitors where Name=#name";
var cmd=new SqlCommand(query,sqlConn);
var cmdParam=cmd.Parameters.Add("#name",SqlDbType.NVarChar,20);
_myVisitorCommand=cmd;
}
...
public int CheckIDVisitor(visitorName)
{
using (var sqlConn=new SqlConnection(Properties.Default.MyDbConnectionString))
{
_myVisitorCommand.Parameters.["#name"]Value=visitorName;
_myVisitorCommand.Connection=sqlConn;
sqlConn.Open();
var result=(int?)cmd.ExecuteScalar();
return result??0;
}
}
An even better option would be to use a micro-ORM like Dapper.Net to get rid of all this code:
public int CheckIDVisitor(visitorName)
{
using (var sqlConn=new SqlConnection(Properties.Default.MyDbConnectionString))
{
string sql = "SELECT ID FROM Visitors WHERE name=#name"
var result = conn.Query<int?>(sql, new { name = visitorName);
return result??0;
}
}
Or
public int[] CheckIDVisitors(string []visitors)
{
using (var sqlConn=new SqlConnection(Properties.Default.MyDbConnectionString))
{
string sql = "SELECT ID FROM Visitors WHERE name IN #names"
var results = conn.Query<int?>(sql, new { names = visitors);
return results.ToArray();
}
}
Trying to communicate with the database, I am little bit confused about how to pass a value as a parameter(for ex. an itemID) and get back the records that are having this ID.
Here is my stored procedure:
ALTER PROCEDURE [dbo].[sp_lightItem]
(
#itemID INT
)
AS
BEGIN
SELECT [itemID],
[itemName],
[itemLocation],
[itemChBy]
FROM [dbo].[Item]
WHERE itemSystemType='E' and itemID=#itemID ORDER BY itemID DESC;
END
And this is my c# code so far..
public string LoadItemNew(int ItemID)
{
var acf = new AcFunctions();
var newstorevalue = SqlHelper.ExecuteDataset(acf.AcConn(), "sp_lightItem", ItemID);
}
As you can see in stored procedure, what I want is to get back those 4 elements:
[itemID],[itemName],[itemLocation],[itemChBy]
Unfortunately I do not know how to get them back/how to call them in c# function.
Any help is welcome.
i dont have enough repo to comment , can you provide the definition of
AcFunctions();
i am sure you it must be returning ConnectionString
try this
public string LoadItemNew(int ItemID)
{
var acf = new AcFunctions();
var newstorevalue = SqlHelper.ExecuteDataset(acf.AcConn(), "sp_lightItem", new SqlParameter ("#itemID",ItemID));
}
Edit 1
try this
public string LoadItemNew(int ItemID)
{
List<string> testList = new List<string>();
var acf = new AcFunctions();
var newstorevalue = SqlHelper.ExecuteReader(acf.AcConn(), "sp_lightItem", new SqlParameter ("#itemID",ItemID));
if(newstorevalue.HasRows)
{
while(newstorevalue.Read())
{
testList.Add(newstorevalue["itemID"].ToString());
testList.Add(newstorevalue["itemName"].ToString());
testList.Add(newstorevalue["itemLocation"].ToString());
testList.Add(newstorevalue["itemChBy"].ToString());
}
}
}
You can try with this approach, I will use Data Transfer Object for holding data retrieved from database and Execute DataReader for reading.
First of all, you need to create a DTO class, I will call it LightItemDTO
public class LightItemDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public string ChangedBy { get; set; }
}
Note: How to know the type of properties, you can reference this link: SQL Server Data Type Mappings
And now, I will using ADO.NET for execute the stored procedure to get data from database
public IEnumerable<LightItemDTO> GetLightItem(string itemText, string sqlConnectionString)
{
var results = new List<LightItemDTO>();
using (var con = new SqlConnection(sqlConnectionString))
{
using (var cmd = new SqlCommand("sp_lightItem", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ItemID", SqlDbType.VarChar).Value = itemText;
con.Open();
using (var reader = cmd.ExecuteReader())
{
results.Add(new LightItemDTO
{
Id = Convert.ToInt32(reader["itemID"]),
Name = reader["itemName"].ToString(),
Location = reader["itemLocation"].ToString(),
ChangedBy = reader["itemChBy"].ToString()
});
}
}
}
return results;
}
Using DataReader is the best practice with high performance.
ADO.NET is the manual way to achieve this task, you can use some ORM framework for do it easier, such as: Entity Framework, Dapper.NET ...
You could execute stored procedure with parameters in following:
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_lightItem", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ItemID", SqlDbType.VarChar).Value = itemId.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
first of all set the Commandtype as stored procedure and that procedure will return some data which you will save in dataset and then return the data set to where ever you want to populate the data
public DataSet LoadItemNew(int ItemID)
{
var acf = new AcFunctions();
return DataSet ds = SqlHelper.ExecuteDataset(acf.AcConn(),CommandType.StoredProcedure, "sp_lightItem",new SqlParameter("#itemID" ItemID);
}
You can try like this ..
public string LoadItemNew(int ItemID)
{
var acf = new AcFunctions();
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("#itemID", ItemID));
DataSet Ds = SqlHelper.ExecuteDataset(acf.AcConn(),CommandType.StoredProcedure, "sp_lightItem" , parameters.ToArray());
return "ok";
}
I'm querying a database with SQLite. I'm trying to get data from this database, save it in an array, then return to the controller. I need to present this data using a foreach loop in my view.
string sql = "select * from Tasks Where UserId = " + userId.ToString();
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
conn.Open();
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
int i = 0;
while (rdr.Read())
{
//here is what i would do in PHP
$array[$i]['name'] = $rdr[i]["name"];
$array[$i]['key'] $rdr[$i]["key"];
}
}
}
return array;
Firstly, learn to use parameterised queries not string concatenation as this will help prevent SQL injection attacks.
string sql = "select * from Tasks Where UserId = #userId";
Also, if you create a class to represent a record in your Tasks table then you can build instances of this object and return them in a list which will make using the code easier since instead of having untyped arrays, you will have an object with properties (in your view you can do foreach (var task in Model) where Model is a List<Task>.
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
}
var tasks = new List<Task>(); // create a list to populate with tasks
using (var connection = new SQLiteConnection(connString))
{
var command = new SQLiteCommand(sql, conn);
command.Parameters.Add("#userId", userId); // only do .ToString on userId if the column is a string.
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var task = new Task();
task.Id = (int)reader["id"]; // the name of the column in the reader will match the column in the Tasks table.
task.Name = (string)reader["name"];
task.Key = (string)reader["key"];
tasks.Add(task);
}
}
}
return tasks;
Instead of writing all the query logic and creating objects, you can use frameworks called Object Relational Mappers (ORM) to do this for you. There are a number of them around, some more simple than others. A MicroORM may suit your purposes, they are simple and easy to use (I have built one called MicroLite but there are others such as dapper or PetaPoco. If you want something more powerful, NHibernate and Entity Framework are popular choices.