How can I query datetime in SQLite database - c#

Here is my code:
string sql = string.Format("select * from StockInTb ");
DataTable dt = dataAccess.GetDataTable(sql);
UploadService.UploadClient client = new UploadService.UploadClient();
if (client.UpdateTest(dt))
{
MessageBox.Show("suceess");
}
else
{
MessageBox.Show("fail");
}
Here is my dataaccess class:
private static string connString;
private static SQLiteConnection conn;
public SQLiteDataAccess()
{
connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
private void OpenConn()
{
try
{
if (conn == null)
{
conn = new SQLiteConnection(connString);
}
if (conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
private void CloseConn()
{
try
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
public System.Data.DataTable GetDataTable(string sql)
{
DataTable dtResult = new DataTable();
try
{
OpenConn();
SQLiteDataAdapter adpter = new SQLiteDataAdapter(sql, conn);
DataSet ds = new DataSet();
adpter.Fill(ds);//here,I got the error.
if (ds.Tables.Count > 0)
{
dtResult = ds.Tables[0];
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
finally
{
CloseConn();
}
return dtResult;
}
I got the error:
String was not recognized as a valid DateTime.
The database is SQLite, and table StockInTb contains some columns which type is datetime.
I've found some solutions like datetime.toString(s), but that's not what I need.
I don't know how to solve this odd problem. If somebody knows the answers, please tell me.
Thanks.

You can use parameter as below, Assume You have Column called MyDateTime and type is DateTime in your StockInTb Table then your query should be change as below.
Note that #InputDate going to add bay using Command.Parameters.Add method. Need to give the same name in both places and you can directly set parameter from DateTime object ( here it is named as InputDate
Command.CommandText = "select * from StockInTb where MyDateTime = #InputDate";
Command.Parameters.Add("#InputDate", InputDate);

Related

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

Datatable error in c#

I used a datatable for fetching some data from mysql db,my error is
not all code paths return a value
ie return DS.Tables[0] is unable to access inside a loop or if statement.How can i solve this issue?
public DataTable GetAlltheatredet()//I got error here//
{
DataTable myalltheat = GetAllmytheatdet();
foreach (DataRow drow1 in myalltheat.Rows)
{
usermsterid = drow1["UserMasterId"].ToString();
if (usrmid == usermsterid)
{
flag = 1;
break;
}
if (flag == 1)
{
try
{
string connString = "Server=localhost;database=Mytable;uid=root;";
string query = "SELECT * FROM `Mytable`.`Mydata`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
}
}
you have if(flag==1) { ... return ... } you need to add an else statement with either a return or a throw new ...
public DataTable GetAlltheatredet()//I got error here//
{
DataTable myalltheat = GetAllmytheatdet();
foreach (DataRow drow1 in myalltheat.Rows)
{
usermsterid = drow1["UserMasterId"].ToString();
if (usrmid == usermsterid)
{
flag = 1;
break;
}
if (flag == 1)
{
try
{
string connString = "Server=localhost;database=Mytable;uid=root;";
string query = "SELECT * FROM `Mytable`.`Mydata`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
else {
throw new Exception("Flag isn't 1 and I don't know what to do");
}
}
}
that's a well known error, if your method that return DataType have any multi path blocks like if {} else {} or switch case, you should return something in every path of them.

select command error on refreshing page continuously

I am developing a banking application in which I have written a helper class.
What happens is whenever I continuously, 5 to 7 or more times, press the refresh button, it gives me this error: Fill: SelectCommand.Connection property has not been initialized.
Can any body specify what I am missing in my code, or what more could I do to make it better to perform without any error?
My helper class function is :
private static OdbcCommand cmd;
private static OdbcDataAdapter da;
private static DataTable dt;
public static void GetDataInDataGrid(string sp_Name, GridView gv)
{
dt = new DataTable();
try
{
using (cmd = new OdbcCommand(sp_Name))
{
cmd.Connection = Connection.ConnString.ConnectionString;
using (da = new OdbcDataAdapter(cmd))
{
da.Fill(dt);
if (dt.Rows.Count > 0)
{
gv.DataSource = dt;
gv.DataBind();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The error is occurring in the below code, at the throw statement
try
{
if (!IsPostBack)
{
herlperUtility.GetDataInDataGrid("{ CALL asp_sp_GetDataForSupervisor }", this.gvSuperviseDataGrid);
if (this.gvSuperviseDataGrid.DataSource == null)
{
this.divFailure.InnerText = "No Records Found!!!";
this.divFailure.Attributes.Add("style", "display:block;margin-top:20px;");
}
}
}
catch (Exception ex)
{
throw ex;
}
Write
using (cmd = new OdbcCommand(sp_Name,Connection.ConnString.ConnectionString))
inplace of
using (cmd = new OdbcCommand(sp_Name))
{
cmd.Connection = Connection.ConnString.ConnectionString;

Repeated SQL Connections, should I create a class?

I'm still quite new to c# and I have multiple count queries on a single page. I don't need to use these queries anywhere else so have avoided creating a class. Still though, I can help but think there must be a more efficient approach but I was wondering what that would be!
Here's an example
private void cntUp() {
Dictionary<string, string> crd = getCredentials(Session["secure"].ToString());
Label UserUpcoming = frmDash.FindControl("lblUserReviewUp") as Label;
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["CS"].ConnectionString))
{
con.Open();
try
{
using (SqlCommand countUpcoming = new SqlCommand("SELECT COUNT(*) FROM vw_dash_user_upcoming WHERE Employee_ID = #employee_id", con))
{
countUpcoming.Parameters.Add(new SqlParameter("employee_id", crd["employee_id"].ToString()));
SqlDataReader readerUpcoming = countUpcoming.ExecuteReader();
while (readerUpcoming.Read())
{
UserUpcoming.Text = readerUpcoming.GetInt32(0).ToString();
}
}
con.Close();
}
catch
{
Response.Redirect(this.ErrorPage);
}
}
}
The following Repository works with SQL Server.
Basically, you can either issue a regular or parameterized query.
You can pass in your parameters as all strings, or just as objects if you are going to use models with strongly typed numbers and dates.
You can take out the Release mode info if you don't use such a construct in developement, this is just to make it easier to switch between development and production databases without coding a change.
An example usage would be :
var updateStatement = "UPDATE OCCHistoryHeaders SET ValidatingUsername=#pUsername,ValidatingWorkstation=#pWorkstation,CurrentState = #pCurrentStatus,RejectionReason = #pRejectionReason, AutomatedValidation = '0' WHERE BatchId = #pBatchId";
var parameters = new Dictionary<string, object>
{
{"pUsername", Environment.UserName},
{"pWorkstation", Environment.MachineName},
{"pCurrentStatus", currentStatus},
{"pRejectionReason", rejectionReason},
{"pBatchId", batchId}
};
var absRowsUpdated = _occDb.ExecuteParameterizedNonQueryObjects(updateStatement, parameters);
Here is the class...
public class SomeRepository
{
private string _connectionString { get; set; }
private SqlConnection _sqlConnection { get; set; }
public SomeRepository()
{
switch (AppSettings.ReleaseMode)
{
case ReleaseMode.DEV:
_connectionString = "server=;database=;User Id=;Password=";
break;
case ReleaseMode.PRODUCTION:
_connectionString = "server=;database=;User Id=;Password=";
break;
}
}
public DataTable ExecuteQuery(string commandText)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public DataTable ExecuteParameterizedQuery(string commandText, Dictionary<string, string> parameters)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public DataTable ExecuteParameterizedQueryObjects(string commandText, Dictionary<string, object> parameters)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public int ExecuteNonQuery(string commandText)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
try
{
var cmd = new SqlCommand(commandText, _sqlConnection);
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
public int ExecuteParameterizedNonQuery(string commandText, Dictionary<string, string> parameters)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
var cmd = new SqlCommand(commandText, _sqlConnection);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
public int ExecuteParameterizedNonQueryObjects(string commandText, Dictionary<string, object> parameters)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
var cmd = new SqlCommand(commandText, _sqlConnection);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
}
If you only do stuff 1 place, generally you'd make everything less readable. So I would probably avoid it. It's a common pattern, however, to you would do yourself a favor writing a utility class with some functions for this.
//requires query parameters to have names #0, #1 etc in string
public static List<object[]> Query(String query, params String[] parameters) //no injection check on this string, be careful.
{
using(SqlConnection conn = new SqlConnection(_CONN_STRING_))
{
conn.Open()
using(SqlCommand cmd = new SqlCommand(query, conn))
{
AddSqlParams(cmd, parameters);
return Query(cmd);
}
}
}
/// <summary>Generic SQL query. Requires open connection.</summary>
/// <param name="cmd">SqlCommand object with all necessary fields configured.</param>
/// <returns>A list of Object arrays (each array is one row).</returns>
private static List<Object[]> Query(SqlCommand cmd)
{
List<Object[]> results = new List<Object[]>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Object[] row = new Object[rdr.VisibleFieldCount];
rdr.GetValues(row);
results.Add(row);
}
return results;
}
}
private static void AddSqlParams(SqlCommand cmd, params String[] sqlParams)
{
for (Int32 i = 0; i < sqlParams.Length; i++)
cmd.Parameters.AddWithValue("#" + i, (Object)sqlParams[i] ?? DBNull.Value);
}
Then use like
UserUpcoming.Text = Query("SELECT COUNT(*) FROM vw_dash_user_upcoming WHERE Employee_ID = #0", crd["employee_id"].ToString())[0][0];
I like to have a separate class for each table in the database. In your case I would have a separate class called vw_dash_user_upcoming, this would have a static method something like...
public static int CountEmployees(int employeeId) {
int returnValue;
// do database stuff here
return returnValue;
}
I usually create a folder and namespace in my project called "database" and all the database stuff goes in there. Nothing goes in there that's not database access. For me this really helps keep things organized, especially in a large project.
Personally I would create a separate class, simply because it's not a good idea to keep pieces of code with totally different responsibilities in one class. When divided into small classes code is easier to read and maintain.
Communication with database should be separated anyway to make it easier to switch between datasources (e.g. different database servers).

How to using oracledataadapter with transaction?

I use a method to gettable using a Select statiments.When i use a select statiment using a link database i got error (ORA-01453 SET TRANSATION must be first statement of transation.)
I know solition but i cant use Transaction methot with Oracledataadapter.
I want to use Commit() ... Rollback().
This is my code:
private System.Data.DataTable GetDataTable_(string SqlStatement, bool fromProcCall)
{
OracleConnection Con = new OracleConnection();
try
{
Con = Connection();
OpenConnection(Con, fromProcCall);
//-----------------------------------------
DateTime startTime = DateTime.Now;
//-----------------------------------------
DataSet ds = new DataSet();
OracleDataAdapter sda = new OracleDataAdapter(SqlStatement, Con);
sda.Fill(ds, "tbl1");
//-----------------------------------------
if (!fromProcCall)
DurationOfIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
else
DurationOfFirstIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
//-----------------------------------------
CloseConnection(Con);
return ds.Tables[0];
}
catch (Exception ex)
{
if (Con != null)
{
try
{
CloseConnection(Con);
}
catch (Exception) { }
}
throw new Exception("ERROR[" + ex.Message + "]");
}
}
Basically, you could do something like this:
oraConn = new OracleConnection("CONNECTION STRING");
oraConn.Open();
//Command with transaction
OracleCommand oraCom = oraConn.CreateCommand();
oraCom.CommandText = "INSERT QUERY";
oraCom.Transaction = oraCom.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
//Execute
if (oraCom.Connection.State == ConnectionState.Closed)
{
oraCom.Connection.Open();
}
oraCom.ExecuteNonQuery();
//Commit / Rollback
oraCom.Transaction.Commit(); // or oraCom.Transaction.Rollback();
To use this with DataAdapter, the concept is the same: Create the transaction setting the DataAdapter.SelectCommand.Transaction and then you can control with Commit() and Rollback().

Categories