I am passing xml to a stored procedure and it is compiling but no row inserted into the database.
My code
foreach (int item in objDirectory.PhotoId)
{
//roots = roots + "<row DirectoryId='"+objDirectory.DirectoryId+"'PhotoId='" +item+"'CreatedBy='"+"Admin"+"'ModifiedBy='"+"Admin"+"'/>";
roots = roots + "<row DirectoryId= '" + objDirectory.DirectoryId + "' PhotoId='" + item + "' CreatedBy ='" + "Admin" + "' ModifiedBy ='" + "Admin" + "'/>";
}
PhotoIds = string.Format(PhotoIds, roots);
objDirectory.SavePhotoId(PhotoIds);
Save Method
public void SavePhotoId(string PhotoId)
{
SqlTransaction tran = null;
try
{
SqlParameter[] arParams = new SqlParameter[3];
m_objConn = new SqlConnection(m_strConn);
m_objConn.Open();
tran = m_objConn.BeginTransaction();
arParams[0] = new SqlParameter("#PhotoID", PhotoId);
SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, "InsertUpdatePhotIdInAlbum", arParams);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (m_objConn.State == ConnectionState.Open)
{
m_objConn.Close();
m_objConn = null;
}
}
}
Stored procedure:
CREATE Procedure [dbo].[InsertUpdatePhotIdInAlbum]
#PhotoID xml=null
As
Begin
set nocount on;
if #PhotoID IS NULL
Begin
Return;
End
Declare #PhotoAlbumDetail TABLE (AlbumID int, PhotoId int, CreatedBy varchar(50),
ModifiedBy varchar(50))
insert into #PhotoAlbumDetail(AlbumID, PhotoID, CreatedBy, ModifiedBy)
select
t.c.value('./#DirectoryId', 'int') as AlbumID,
t.c.value('./#PhotoId', 'int') as PhotoID,
t.c.value('./#CreatedBy', 'varchar(50)') as CreatedBy,
t.c.value('./#ModifiedBy', 'varchar(50)') as ModifiedBy
from
#PhotoID.nodes('/root/row') t(c);
INSERT INTO [dbo].[tbl_PhotoAlbumDetail](AlbumID, PhotoId, CreatedBy, ModifiedBy)
SELECT
p.AlbumID, p.PhotoId, p.CreatedBy, p.ModifiedBy
FROM
#PhotoAlbumDetail p
End
Related
I would like to delete a row in tableview but also in the
underlying SQLite Database which populate the tableview
Here I get the selectedRow
public void deleteDBRow() {
if (tableV.getSelectionModel().getSelectedItem() != null) {
Bew selBew = tableV.getSelectionModel().getSelectedItem();
System.out.println(selBew.getName());
}
}
and can delete it with casual code
DELETE FROM Table WHERE name = ""+selBew.getName()");
But I would like to delete the entry in the sqlite database also
From time to time I have rows with the same text in every column - so this way
was critical - can I use rowID to delete the selected row in sqlite?
Here one try from me to get rowid in tableview
ObservableList bewList = FXCollections.observableArrayList();
try {
String sql = "SELECT rowID, Name, Date, Action, Info FROM tab1";
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB1.db");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
bewList.add(new Bew(rs.getInt("rowID"), rs.getString("name"), rs.getString("date"),
rs.getString("action"), rs.getString("Info")));
System.out.println("rs.next : " + rs.getInt("rowID") +" - " + rs.getString("date") +" " +
rs.getString("action") +" " + rs.getString("Info"));
}
}catch (Exception e) {
System.out.println("SQLiteDB.getData ---> Error RS");
System.err.println("*E"+e.getClass().getName() + ": " + e.getMessage());
}
return bewList;
String sql = "CREATE TABLE IF NOT EXISTS tab1" +
"(rowID INT PRIMARY KEY," +
"NAME CHAR(50) NOT NULL ,"+
"DATE CHAR(15) ,"+
"ACTION CHAR(50) ,"+
"INFO CHAR(3));";
conn.createStatement().executeUpdate(sql);
rowID ist always 0 - don't know why ???
edit:
Controller
ObservableList bewList = DB.getData();
tableV.setItems(bewList);
Edit:
Maybe error in here - add data
i add 4 values - rowid missing??
public void add(String Name, String Date, String Action, String Info) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB2.db");
stmt = conn.createStatement();
String ValStr = "\'"+Name+"\' ,\'"+Date+"\',\'"+Action+"\' ,\'"+Info+"\'";
String sql = "INSERT INTO tab1 (rowID, NAME,DATE,ACTION, INFO) VALUES ("+ValStr+")";
// System.out.println("Button Click add"+conn.createStatement().toString());
stmt.executeUpdate(sql); //geƤndert
ObservableList<Bew> list = getData();
conn.close();
System.out.println("DB ROW add");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
I want to get all records with timestamp of a current day. According to [this][1] I creating query
SELECT *
FROM table
WHERE timestamp BETWEEN date('now', 'start of day', 'localtime', 'unixepoch') AND
date('now', 'start of day','+1 day', 'localtime', 'unixepoch')"
but allways got nothing. I updating some records calling System.currentTimeMillis()/1000 function. I try without unixepoch parameter but still got nothing
EDIT: I paste my code I try to set timestamp column with diffrent types but it doesnt help too mutch
private static final String DATABASE_CREATE = "create table if not exists "
+ TABLE_DAILY_CHALLENGES +
"(" + DAILY_CHALLENGES_ID + " integer primary key autoincrement, " +
DAILY_CHALLENGES_TITLE + " text not null, "+
DAILY_CHALLENGES_CONTENT + " text not null, "+
DAILY_CHALLENGES_COUNTER + " text not null, "+
DAILY_CHALLENGES_SORT+ " integer not null, " +
DAILY_CHALLENGES_ACTUAL_COUNTER+ " text not null, " +
DAILY_CHALLENGES_TIMESTAMP+ " integer DEFAULT 0, " +
DAILY_CHALLENGES_FINISHED+ " integer DEFAULT 0, " +
DAILY_CHALLENGES_TYPE + " text not null);";
private static Database getDbHandlerInstance(){
if(dbHandler==null){
return init();
}else
return dbHandler;
}
private static Database init(){
dbHandler = DatabaseFactory.getNewDatabase(DATABASE_NAME,
DATABASE_VERSION, DATABASE_CREATE, null);
dbHandler.setupDatabase();
try {
dbHandler.openOrCreateDatabase();
dbHandler.execSQL(DATABASE_CREATE);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
try { //TODO:: make it more efficient
String query="SELECT * FROM dailyChallenges";
DatabaseCursor cursor = dbHandler.rawQuery(query);
if(cursor.getCount()!=NUMBERS_OF_RECORDS){
cleanTable();
populateDatabase();
}
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
return dbHandler;
}
private static void cleanTable() {
try {
dbHandler.execSQL("delete from "+ TABLE_DAILY_CHALLENGES);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
}
public static Challenge[] getChallenge(){
DatabaseCursor cursor=null,cursorAll=null;
Challenge[] challenge;
try {
String query="SELECT * FROM dailyChallenges WHERE timestamp BETWEEN date('now', 'start of day', 'localtime', 'unixepoch') AND date('now', 'start of day','+1 day', 'localtime', 'unixepoch')";
cursor = getDbHandlerInstance().rawQuery(query);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
//create new challenge
if(cursor.getCount()!=0){
//logic,cursor.getCount() is always 0}
I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.
I am struggling with testing if there is specific data in my SQLite database.
The method accepts a subject code, person id, and a table name. I am 100% sure those 3 things are correct.
What this should do is try to select a record. If the record can be selected return -1, otherwise return 0.
My problem is the datareader does not seem to be reading any records, when there is records in my database.
public int TestIfExists(string subID, string personID, string table)
{
_sqlConnection = new SQLiteConnection(_conStr);
bool dataRead = false;
int rc = 0;
try
{
string selectQuery = "SELECT * FROM " + table + " WHERE PersonID = '" +
personID + "' AND SubjectCode = '" + subID + "'";
_sqlConnection.Open();
SQLiteCommand sqlCommand = new SQLiteCommand(selectQuery, _sqlConnection);
IDataReader idr = sqlCommand.ExecuteReader();
dataRead = idr.Read();
if (dataRead == true)
{
rc = -1;
}//end if
else
{
rc = 0;
}//end else
idr.Close(); // Closed IDataReader
}//end try
catch (SQLiteException sqlEx) // Catch SQLiteException
{
MessageBox.Show(sqlEx.ToString());
throw new DataStoreError(sqlEx.Message);
}//end catch
catch (Exception ex)
{
throw ex;
}//end catch
finally
{
_sqlConnection.Close();
}//end finally
return rc; //Single return
}
When you are trying to see if it exists or no, you can do a
SELECT Count(*) FROM Table WHERE (...)
and this way 0 would means doesn't exists, other wise yes.
Okay,The Other errors are fixed now im at this point where my other pages need their code to be updated:
Error : Object reference not set to an instance of an object.
public partial class Controls_GetUserScraps : System.Web.UI.UserControl
{
DataBaseClass dbClass = new DataBaseClass();
public DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetUserScraps(int.Parse(Session["UserId"].ToString()));
}
}
public void GetUserScraps(int Id)
{
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
dt = dbClass.ConnectDataBaseReturnDT(getUserScraps);
if (dt.Rows.Count > 0)
{
GridViewUserScraps.DataSource = dt;
GridViewUserScraps.DataBind();
}
}
I replaced Session ID to UserId and it removed the error now it has displayed another error under.
Error : Object reference not set to an instance of an object.
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
Adding your fix created this new error:
I think the easiest way to do this would be to have the private bool UserAuthenticate method take an out parameter which you can use to return the actual user name from the database.
private bool UserAuthenticate(string UserName, string Password, out string actualUserName)
{
actualUserName = string.Empty;
bool boolReturnValue = false;
//--------------------------------
//Check UserID From Config File
if (UserName == "User" && Password == "Pass")
{
boolReturnValue = true;
return boolReturnValue;
}
else
{
//--------------------------------
dt = new DataTable();
string chkUser = "Select * FROM [User] where Email='" + UserName + "' AND Password='" + Password + "'";
dt = dbClass.ConnectDataBaseReturnDT(chkUser);
if (dt.Rows.Count > 0)
{
//TODO: grab the actual user name from the row and assign it to actualUserName. For example:
actualUserName = dt.Rows[0]["FullName"];
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
}
After that you would then need to do something like this in the OnAuthenticate method:
string actualUserName;
Authenticated = UserAuthenticate(ctlLogin.UserName, ctlLogin.Password, out actualUserName);
And the redirect would now be:
Response.Redirect("Home.aspx/" + actualUserName);