Saving SQLite query results as variables - c#

So basically I'm looking to try to make a basic login for a WPF app and store certain user data into variables with C#. Problem I'm running into is separating the result of different datatypes into variables to use later in the app. Something similar to the GET command in PHP. I have seen some documentation about creating a separate class replicating the data you need and could probably run individual queries for each variable, but that just feels wrong and I know there's a better way.
Here is my code so far:
Database databaseObject = new Database();
var userid = LoginTextBox.Text;
string query = "SELECT * FROM users WHERE userid = #userid";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("#userid", userid);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
/* GET RESULT INTO VARIABLES */
}
else
{
LoginTextBox.Text = "";
}
databaseObject.CloseConection();
Don't think I'm too off here just need a push in the right direction :)

You can create a User class that has all the properties coming back from the table.
Something like:
public class User {
public int UserId { get; set }
public string UserName { get; set; }
}
And then just read the properties from your SQLiteDataReader and assign them to the properties of the class:
var user = new User();
user.UserId = (int)result["userid"];
user.UserName = (string)result["username"];

Related

local variable might be not initialized before accessing c#

So i try to get around this issue. I know for a fact that this will be initialized before am calling it but c# can not know this i guess.
I cannot do xUser user = new xUser;
One work around i was thinking about was using an List and store the values in list and then create the xuser after the while loop but it seems very messy. And i really wanna learn how to avoid this kind of errors.
noUSer iuser = new noUSer();
xUser user;
string sql = "select * from accounts where id='" +id +"'";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
iuser.user_name = reader["login"].ToString();
iuser.password = reader["password"].ToString();
iuser.cookie_file = #"c:\cookies";
user = iusers.create(iguser);
}
m_dbConnection.Close();
if (tab_mode.SelectedTab.Text == "User")
{
dothiscall(user); //Error on "user" local variable might be not initialized before accessing
}
You should initialize the variable to null, however, be aware that if the code inside while loop doesn't execute, it will remain null.
Yes better way is create a list iusers and add new iuser inside while loop. and your whileloop to user you are adding iguser which can not find. It should be iuser
xUser user = new xUser();
string sql = "select * from accounts where id='" +id +"'";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
noUSer iuser = new noUSer();
iuser.user_name = reader["login"].ToString();
iuser.password = reader["password"].ToString();
iuser.cookie_file = #"c:\cookies";
user = iusers.Add(iuser);
}
When you do:
xUser user;
You are merely creating a pointer.meaning if u had an object of type xUser later on and wanted a pointer to it you could do for example something like :
user =(xUser)DataGridView1.Rows[0].cells[myxUserObjectInCell.index].Value;
That way making changes to user will make changes to the object in your grid.
However if you're planning on creating an object of type xUser,then you need to do:
xUser user = new xUser();
The new keyword makes it initialize.

How to retrieve table dynamically using only one controller?

I am using the following code as a controller for a single table to access the table from my database, and assign values of each column to a variable. However, I have many tables(Booktrans in this case) and I want to use a single controller that can access all the tables using table ID as a variable. After that, assigning values of different columns from different tables will also be different from the code below. Could anyone help me with a "dynamic" way of coding to replace this controller for a specific table with a dynamic controller?
I am using MVC4.
All the tables have different structures and different column names.
public ActionResult Booktrans()
{
String connectionString = "Dsn=SECURE;Uid=internwebuser";
OdbcConnection conn = new OdbcConnection(connectionString);
String sql = "SELECT * FROM booktrans";
OdbcCommand cmd = new OdbcCommand(sql, conn);
var model = new List<Booktrans>();
using (conn)
{
conn.Open();
OdbcDataReader rdr = cmd.ExecuteReader();
//model = new List<Booktrans>();
while (rdr.Read())
{
var book = new Booktrans();
book.ship_last_name = rdr["ship_last_name"].ToString();
book.ship_first_name = rdr["ship_first_name"].ToString();
book.ship_zip = rdr["ship_zip"].ToString();
book.ship_state = rdr["ship_state"].ToString();
book.ship_address = rdr["ship_address"].ToString();
book.ship_city = rdr["ship_city"].ToString();
book.day_phone = rdr["day_phone"].ToString();
book.email_address = rdr["email_address"].ToString();
model.Add(book);
}
}
return View(model);
}
How about you use an actual ORM, since that's what you're trying to reverse-engineer here. With something like Entity Framework, you create an entity class that maps to a particular table and that has properties that map to columns in that table. Then, with Entity Framework, in particular, you add a DbSet that represent the collection of rows in this table to your context:
public DbSet<Foo> Foos { get; set; }
With that, you can then simply use the API Entity Framework provides to interact with that data:
// Get specific Foo
var foo = db.Foos.Find(id);
// Get matching Foos
var foos = db.Foos.Where(m => m.Bar == "bar");
// Add a new Foo
db.Foos.Add(new Foo { Bar = "bar" });
So on and so forth. Other ORMS like NHibernate have slight different setups and API, but they all basically behave the same and don't require that you worry about generating SQL.

How can I reference data of DataGridView into SQL database in C#?

I am new to database and C#. I am building an EPOS software and I just want to
reference the data which is in DataGridView into SQL database (if I am saying it correct).
Ok, here is what I am trying to do:
as shown in the photo, I have customer1 order details (3 rows) in DataGridView and this details is only for one customer1. Now when I finish with customer1, its order details is saved in database. Next, when I finish with customer2 order, its details is saved in database. Next, customer3 order details will be saved in database.... and so on.
Now for example at some point in the future I want to read back / Edit (or check)
customer2 order details from database and populate it into DataGridView.
I have been thinking how to do it but I failed and I am confused.
Can you please provide me with an idea or code in how to check what did Customer2 order. thank you.
Create a Customer Model which represent your table. Then create a method which will return a collection. I'm going to assume you've got your connection string setup and know how to read it in your code using c#. So the code could look like:
public class Customer
{
public int Quantity { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
public List<Customer> GetCustomerData()
{
var list = new List<Customer>();
string sqlQuery = "SELECT Qty, Des, Price From MyTable Where Customer = SomeCustomer"; //Change accordingly
string connectionString = "Your Connection String";
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sqlQuery, connection))
{
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var c = new Customer();
c.Quantity = Convert.ToInt32(reader["Qty"]);
c.Description = reader["Des"].ToString();
c.Price = Convert.ToDouble(reader["Price"]);
list.Add(c);
}
}
}
}
return list;
}
Finnaly to display the data on the DataGrid you'll do:
MyGrid.ItemsSource = GetCustomerData(); //Change MyGrid to whatever you've named your grid
Please note: I haven't tested the above code so it might require some small changes. However it should give you a good idea.

Store the results in memory (List) using c#

I want to store many record that I query from database in list , one record has 10 fields, in order to loop it later.
But I have no idea to do that. Anyone can answer me please.
Below is a good practice to store data and loop through among them.
Create Model/POCO class as:
public class DataClassName
{
public int Id { get; set; }
public string Name { get; set; }
//Create properties according to your fields
}
Fill and get data list:
public List<DataClassName> GetDataList()
{
List<DataClassName> dataList = new List<DataClassName>();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from TargetTableName";
cmd.CommandType = CommandType.Text;
try
{
using (SqlConnection connection =
new SqlConnection("YourConnectionString"))
{
cmd.Connection = connection;
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
dataList.Add(
new DataClassName()
{
Id = Convert.ToInt32(reader["ID"]),
Name = Convert.ToString(reader["Name"])
//Set all property according to your fields
});
}
}
}
}
catch(Exception ex_)
{
//Handle exception
}
return dataList;
}
Save data that is returned from GetDataList() into your datalist and loop through among the data as required.
Here's how you'd go about storing it in a DataTable:
SqlConnection conn = new SqlConnection("yourConnectionStringHere");
SqlCommand GetData = new SqlCommand();
GetData.Connection = conn;
GetData.CommandText = "select * from yourTable"; // or whatever your query is, whether ad hoc or stored proc
// add parameters here if your query needs it
SqlDataAdapter sda = new SqlDataAdapter(GetData);
DataTable YourData = new DataTable();
try
{
sda.Fill(YourData);
}
catch
{
sda.Dispose();
conn.Dispose();
}
If you have 10 fields, you'd be hard-pressed to store your data in a List<T> object. Your best bet would be to create a class tailored to the data you are looking to retrieve (if you want to take it a step further than the DataTable implementation above) with corresponding properties/fields.
Perhaps you could give a bit more information...
If you use the entity framework or similar to query the database, it will probably return an enumerable object.. you just need to call .ToList() on this to save it as a list.
Do you mean that you want to store this across web requests? Then you could store it in the HttpRuntime.Cache collection, allowing for it to expire after some time.
Alternatively store it in a static property. Session is also an option but it doesn't sound like the best option for this

Retrieve single value from Database, much like DLookup() in MS Access

I am exploring Silverlight (C#) and SQLServer as a next evolution for our current (slow) Access database. So far everything has been great, using DomainServices to retrieve the data I need. In our database we have a table (Supervisors) with Supervisor_ID, Supervisor_FirstName, Supervisor_LastName and many other fields.
What I want to do is recreate a function I use in my current database called EntityNameFirstLast(EntityID) which would take an integer. I could then retrieve the value of [Supervisor_FirstName] from [Supervisors] table where [Supervisor_ID] == EntityID using the following:
FirstName = DLookup("[Supervisor_FirstName]", "Supervisors", "[Supervisor_ID] = EntityID
I would do the same for lastname and combine the strings returning one string with First and last name.
How can I get just a single value from my database through my DomainService (or any way for that matter)? I understand that IQueryable GetSupervisorByID(Int SupID) will return the entire row that I need, but how can I get a specific field from that row?
I am also aware that I can set the DomainDataSource in my XAML and then bind to the data I want, but I am curious if what I asked above is doable or not.
There are number of ways you can accomplish your requirement if what you need is a single value from MS-SQL server:
1.Use a Query to do the concatenation and then use its output in your code
Select Supervisor_FirstName + ' ' + Supervisor_LastName as Supervisor_FullName From Supervisors Where Supervisor_ID = EntityID
Now you can get the above query to execute through a SqlCommand and get the part thats interesting to you
private string GetSupervisorFullName(string entityID, string connectionString) {
string query = "Select Supervisor_FirstName + ' ' + Supervisor_LastName as Supervisor_FullName From Supervisors Where Supervisor_ID = #EntityID";
string supervisorFullname = "";
using(SqlConnection con = new SqlConnection(connectionString)) {
SqlCommand cmdSupervisorFullname = new SqlCommand();
cmdSupervisorFullname.Connection = con;
cmdSupervisorFullname.CommandText = query;
cmdSupervisorFullname.CommandType = CommandType.Text;
SqlParameter paraEntityID = new SqlParameter();
paraEntityID.ParameterName = "#EntityID";
paraEntityID.SqlDbType = SqlDbType.NVarChar;
paraEntityID.Direction = ParameterDirection.Input;
paraEntityID.Value = entityID;
cmdSupervisorFullname.Parameters.Add(paraEntityID);
try {
con.Open();
supervisorFullname = (String) cmdSupervisorFullname.ExecuteScalar();
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
return supervisorFullname;
}
}
2.Second way would be create a Scalar function in the SQL for your requirement and then access that function using the same kind of method as mentioned above.
Then finally you would take the return value from your method GetSupervisorFullName and populate any control value of your choice.
Please do note that there are again other methods of doing the same with LINQtoSQL or with any other ORM tools. The above 2 methods are the basic way of accomplishing them.
Hope that helps.

Categories

Resources