Existing data in database SQLITE + Unity - sqlite

I need to check in the database if the value is current exist. but i don't know how use data in my value public Text CreateUsername.
[SerializeField]
private Text CreateUsername;
Create user query
public void CreateUser(string username, int status)
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string insertuser = String.Format("insert into user_data (UserData_name, UserData_status) values (\"{0}\",\"{1}\")", username, status);
dbCmd.CommandText = insertuser;
dbCmd.ExecuteScalar();
dbConnection.Close();
}
}
}
Insert user query... in this process i don't know what correct query will i use in where condition in String checkusername.
public void insertCreateUser()
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string checkusername = "select count(UserData_name) from user_data where UserData_name ";
dbCmd.CommandText = updatestatus;
dbCmd.ExecuteScalar();
dbConnection.Close();
}
}
ChangeStatus();
int stat = 1;
CreateUser(CreateUsername.text, stat);
}

Related

Web API to query SQL Server and return result is not working as expected

I am trying to connect to SQL Server from the Web API and return a result set as JSON. But my code shown here is not working as expected. I am trying to return the entire query response as a JSON:
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM)
{
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
connection.Close();
return response;
}
}
This code returns this result:
333838362692368203368203368203362692368203359544362692368203362692368203362692368203368203
Where I am expecting the JSON as
{"data":
[
{"R_ID":"368203","ROOM":"K2"},
{"R_ID":"368203","ROOM":"K2"}
]}
Now I created a model class called DatabaseResult to store the response but I am not sure how I can store the result in to the model class in the controller
public class DatabaseResult
{
public int r_id { get; set; }
public string room { get; set; }
}
The current result is because you are only return the the value from the first column of each row and adding it to the string builder.
Create a new instance of the model and populate it using the values from the reader for each row.
[HttpGet]
public IHttpActionResult Getdetails(string ROOM) {
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr)) {
using (SqlCommand command = new SqlCommand(commandText, connection)) {
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
List<DatabaseResult> records = new List<DatabaseResult>();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new DatabaseResult {
r_id = (int)reader["r_id"],
room = (string)reader["room"],
//...other properties.
};
records.Add(row);
}
return Ok(records);
}
}
}
}
The above uses the column names as the indexer to get the values from the reader.

Sqllite SQLiteDataReader returns enpty reader while SQLiteDataAdapter returns the right result

I have trouble with Sqllite SQLiteDataReader. Using the same connection string and the same sql statement SQLiteDataReader returns empty reader while SQLiteDataAdapter returns suspected record.
I this case I try to get the record with the highest value in the Id field.
The database contains several records with unique values in the Id field, but the reader return is empty when using SQLiteDataReader. When I use the same connection string and sql statement with SQLiteDataAdapter suspected results appears. I supply a part of the static class I use for communication with the database. The method SenasteBokning using SQLiteDataReader isn’t working. The method SenasteBokning2 using SQLiteDataAdapter works perfect.
What’s wrong with the method SenasteBokning?
I use:
Windows 10
Visual Studio 2017
.net framework 4.5.2 (Was default at creation of Windows Forms application)
Nuget package System.Data.SQLite.Core 1.0.108
static class Databas
{
private static string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string dbPath = #"\BokningarConvention.db";
private static string connectionString = "Data Source= " + appPath + dbPath;
private static SQLiteConnection con;
private static SQLiteCommand cmd;
private static SQLiteDataReader reader;
private static SQLiteDataAdapter adapter;
private static SQLiteCommandBuilder commandBuilder;
private static DataTable table;
private static string senaste = "SELECT Nummer, NrSammaDag, Datum FROM Bekraftelser WHERE Id = (SELECT MAX (Id) FROM Bekraftelser)";
// This don't work
public static Bokning SenasteBokning()
{
Bokning bokning = new Bokning();
using (SQLiteConnection con2 = new SQLiteConnection(connectionString))
{
con2.Open();
SQLiteCommand cmd2 = new SQLiteCommand(senaste, con2);
SQLiteDataReader reader2 = cmd2.ExecuteReader();
// Here the reader is empty
while (reader2.Read())
{
// Error at first read
// should handle results the same way as in SenasteBokning2
// removed during testing
}
}
return bokning;
}
//This works perfekt
public static Bokning SenasteBokning2()
{
Bokning bokning = new Bokning();
using (SQLiteConnection db = new SQLiteConnection(connectionString))
{
adapter = new SQLiteDataAdapter(senaste, connectionString);
commandBuilder = new SQLiteCommandBuilder(adapter);
table = new DataTable();
db.Open();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
int nummer;
int samma;
DateTime datum;
nummer = (int)((long)row["Nummer"]);
datum = Verktyg.FromDateInteger((int)((long)row["Datum"]));
if (!row.IsNull("NrSammaDag"))
{
samma = (int)((long)row["NrSammaDag"]);
bokning = new Bokning(nummer, samma, datum);
}
else
{
bokning = new Bokning(nummer, datum);
}
}
}
return bokning;
}
}

C# & Asp.Net : transfer files from SQL Server to browser client, without save on application server

I have an application that persists big files with more 2,5 Gb. When client request to download this file, I want that the file goes to the client browser without save on application server as I do today.
I'm using SQL Server 2008 R2, Asp.Net 3.5, and the column that stores the file is of datatype Varbinary.
I went through the same situation and got the solution in this post. You will use the VarbinaryStream class as follows:
Original Post here.
VarbinaryStream filestream = new VarbinaryStream(
DbContext.Database.Connection.ConnectionString,
"FileContents",
"Content",
"ID",
(int)filepost.ID,
true);
Code:
public class VarbinaryStream : Stream
{
private SqlConnection _Connection;
private string _TableName;
private string _BinaryColumn;
private string _KeyColumn;
private int _KeyValue;
private long _Offset;
private SqlDataReader _SQLReader;
private long _SQLReadPosition;
private bool _AllowedToRead = false;
public VarbinaryStream(
string ConnectionString,
string TableName,
string BinaryColumn,
string KeyColumn,
int KeyValue,
bool AllowRead = false)
{
// create own connection with the connection string.
_Connection = new SqlConnection(ConnectionString);
_TableName = TableName;
_BinaryColumn = BinaryColumn;
_KeyColumn = KeyColumn;
_KeyValue = KeyValue;
// only query the database for a result if we are going to be reading, otherwise skip.
_AllowedToRead = AllowRead;
if (_AllowedToRead == true)
{
try
{
if (_Connection.State != ConnectionState.Open)
_Connection.Open();
SqlCommand cmd = new SqlCommand(
#"SELECT TOP 1 [" + _BinaryColumn + #"]
FROM [dbo].[" + _TableName + #"]
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
_SQLReader = cmd.ExecuteReader(
CommandBehavior.SequentialAccess |
CommandBehavior.SingleResult |
CommandBehavior.SingleRow |
CommandBehavior.CloseConnection);
_SQLReader.Read();
}
catch (Exception e)
{
// log errors here
}
}
}
// this method will be called as part of the Stream ímplementation when we try to write to our VarbinaryStream class.
public override void Write(byte[] buffer, int index, int count)
{
try
{
if (_Connection.State != ConnectionState.Open)
_Connection.Open();
if (_Offset == 0)
{
// for the first write we just send the bytes to the Column
SqlCommand cmd = new SqlCommand(
#"UPDATE [dbo].[" + _TableName + #"]
SET [" + _BinaryColumn + #"] = #firstchunk
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#firstchunk", buffer));
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
cmd.ExecuteNonQuery();
_Offset = count;
}
else
{
// for all updates after the first one we use the TSQL command .WRITE() to append the data in the database
SqlCommand cmd = new SqlCommand(
#"UPDATE [dbo].[" + _TableName + #"]
SET [" + _BinaryColumn + #"].WRITE(#chunk, NULL, #length)
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#chunk", buffer));
cmd.Parameters.Add(new SqlParameter("#length", count));
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
cmd.ExecuteNonQuery();
_Offset += count;
}
}
catch (Exception e)
{
// log errors here
}
}
// this method will be called as part of the Stream ímplementation when we try to read from our VarbinaryStream class.
public override int Read(byte[] buffer, int offset, int count)
{
try
{
long bytesRead = _SQLReader.GetBytes(0, _SQLReadPosition, buffer, offset, count);
_SQLReadPosition += bytesRead;
return (int)bytesRead;
}
catch (Exception e)
{
// log errors here
}
return -1;
}
public override bool CanRead
{
get { return _AllowedToRead; }
}
#region unimplemented methods
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
throw new NotImplementedException();
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
#endregion unimplemented methods
}

Losing first record and the values keep changing when loading reader to datatable

I load reader to my table like this
connection.Open();
sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable dt = new DataTable();
sqlReader.Read();
dt.Load(sqlReader);
But it looks like I cannot retrieve the first record of fetch data.
The second problem is when I call the reader several times after that:
string comName = dt.Rows[0]["companyName"].ToString();
//To get address
sqlCmd.CommandText = addr;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var addressReader = sqlCmd.ExecuteReader())
{
if (addressReader.Read())
{
Label1.Text = Label1.Text + " " + addressReader["address"].ToString();
}
}
//To get keyProcesses
sqlCmd.Parameters.Clear();
sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var keyProcessesReader = sqlCmd.ExecuteReader())
{
if (keyProcessesReader.Read())
{
Label1.Text = Label1.Text + " " + keyProcessesReader.GetString(0);
}
}
But I find out that these reading also may changes the value of my datatable dt above! How could I only load data to dt at the first reading and keep it there without changing any more ?
Ps: In attempt to overcome the second problem, I am trying to store dt values in list
public class CompanyModel
{
public string compnName { get; set; }
public string compnAddress { get; set; }
public string compnKeyProcesses { get; set; }
public string compnStandards { get; set; }
}
then
List<CompanyModel> companies = new List<CompanyModel>();
for(int i = 0; i < dt.Rows.Count; i++)
{
companies.Add(new CompanyModel
{
compnName = dt.Rows[i]["companyName"].ToString(),
compnAddress = dt.Rows[i]["address"].ToString()
});
}
companyRepeater.DataSource = companies;
companyRepeater.DataBind();
Now, how do I access each company name in the list to make query on that name value accordingly, then input the new result to the list?
I tried:
foreach(List<Component> compnName in companies.Contains("companyName")
{
sqlCmd.CommandText = getKey;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var keyReader = sqlCmd.ExecuteReader())
{
if (keyReader.Read())
{
companies.Add(new CompanyModel compnKeyProcesses = keyReader.GetString("key"));
}
}
sqlCmd.CommandText = getstandard;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var standardReader = sqlCmd.ExecuteReader())
{
if (standardReader.Read())
{
companies.Add(new CompanyModel compnStandards = keyReader.GetString("standards"));
}
}
Try this for your first problem
SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
DataTable dt=new DataTable();
sdr.Fill(dt);
you can display this whole data as a matter of confirmation by taking a datagridview
dataGridView1.DataSource=dt;

Session variable accessibility

I have a class which creates a session the following way:
Session["UserId"] = UserId; // UserId = 1
In one of the pages on Page_Load, I retrieve the session variable value this way which works fine:
if (Session["UserId"] != null){
var userid = Session["UserId"];
Welcome.Text = "Hello, " + userid;
}
Now I need to use the value of the session variable in my classes as well. I used the following method to get the session value int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]); but it always returns null whereas the session is correctly read using Session["UserId"]; in my code behind file.
The mentioned class:
public static DataTable ManageBookingsDataTable()
{
int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]);
SqlConnection con = new SqlConnection(Database.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select bookings.id,user_id, start_date, end_date, pets.name AS 'Pet name' from bookings AS bookings left join users AS usr ON bookings.user_id=usr.id AND bookings.user_id=1 left join pets AS pets ON pets.id=bookings.pet_id WHERE bookings.user_id=#userid_session", con);
cmd.Parameters.AddWithValue("#userid_session", useridsession);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
string id = string.Empty;
string name = string.Empty;
string startdate = string.Empty;
string enddate = string.Empty;
string full_string = string.Empty;
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
id = dt.Rows[i]["id"].ToString();
var sdate = dt.Rows[i]["start_date"];
name = dt.Rows[i]["Pet name"].ToString();
startdate = dt.Rows[i]["start_date"].ToString();
enddate = dt.Rows[i]["end_date"].ToString();
full_string = startdate + " to " + enddate + " (" + name + ")";
//CurrentBookings.Items.Add(new ListItem(full_string, id));
}
}
return dt;
}
I diagnosed the problem by adding HttpContext.Current.Session["UserId"] = 1; which proves that when I set the session in the same class, the method works.
My question is how do I access the previously created session from any class?
Session should be available for the session regardless of the class. Why don't you set and get
your session values using the same class? All your session stuff in a one place so it is more neat and tidy as well.
Local.MySession.UserId = UserId; //Set here
int myUserId = Local.MySession.UserId; //Get here
//Something like this??
namespace Local
{
//You can add all session variables to this class
public class MySession
{
public static int UserId
{
get
{
return Convert.ToInt32(HttpContext.Current.Session["userId"] ?? "0");
}
set { HttpContext.Current.Session["userId"] = value.ToString(); }
}
public static string UserEmail //For Example another session variable
{
get { return HttpContext.Current.Session["email"] ?? ""; }
set { HttpContext.Current.Session["email"] = value; }
}
}
}

Resources