In my Windows Forms application, I'm using a SQL Server Compact database. I have a function in which I want to update the columns 'id' and 'name' in table 'owner', unless the specified id does not exist, in which case I want new values inserted.
For example, my current table has 'id' 1 and 2. It MIGHT have 'id' 3. User enters data to insert/update id 3.
I want my query to do something like this:
UPDATE owner
SET name = #InputN
WHERE id = 3
IF ##ROWCOUNT = 0
INSERT INTO owner (id, name) VALUES 3, #InputN
How should I define my query in order to make this work in SQL Server Compact Edition?
You should do it in your form codes. This way you don't even need to check if there is an di with the value=3. It will check it by itself and update the row if it exists. If not you won't get any errors.
RSSql.UpdateNonQueryParametric("update owner set name=? where id=3", newname);
public static void UpdateNonQueryParametric(string query, params Object[] parameters)
{
SqlCeParameter[] param = new SqlCeParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
param[i] = new SqlCeParameter();
param[i].Value = parameters[i];
}
_cnt = new SqlCeConnection();
_cnt.ConnectionString = ConnectionString;
_cmd = new SqlCeCommand();
_cmd.Connection = _cnt;
_cmd.CommandType = System.Data.CommandType.Text;
_cmd.CommandText = query;
_cmd.Parameters.AddRange(param);
if (_cnt.State != System.Data.ConnectionState.Open)
_cnt.Open();
_cmd.ExecuteNonQuery();
_cmd.Dispose();
if (_cnt.State != System.Data.ConnectionState.Closed)
_cnt.Close();
_cnt.Dispose();
}
Related
I need to insert records to an Oracle DB table that already has records in it by using the table's sequence.
I tried using RQL which creates an auto-generated id for the primary key but sometimes those generated ids already exist in the database and as a result, a constraint violation error is thrown.
ATG documentation provides an alternative named Overriding RQL-Generated SQL but I didn't manage to make it work for insert statements.
GSARepository repo =
(GSARepository)request.resolveName("/examples/TestRepository");
RepositoryView view = repo.getView("canard");
Object params[] = new Object[4];
params[0] = new Integer (25);
params[1] = new Integer (75);
params[2] = "french";
params[3] = "greek";
Builder builder = (Builder)view.getQueryBuilder();
String str = "SELECT * FROM usr_tbl WHERE (age_col > 0 AND age_col < 1
AND EXISTS (SELECT * from subjects_tbl where id = usr_tbl.id AND subject
IN (2, 3)))";
RepositoryItem[] items =
view.executeQuery (builder.createSqlPassthroughQuery(str, params));
Is there any way to use table's sequence for insert statements via ATG Repository API?
Eventually, I did not manage to make it work but I found the following solution.
I retrieved the sequence number as below and then used it in the RQL insert statement.
RepositoryView view = getRestServiceDetailsRepository().getView("wsLog");
String sql = "select log_seq.nextval from dual";
Object[] params = {};
Builder builder = (Builder) view.getQueryBuilder();
Query query = builder.createSqlPassthroughQuery(sql, params);
RepositoryItem[] items = view.executeQuery(query);
if (items != null && items.length > 0) {
items[0].getRepositoryId();
}
I am lost on where to go next, I have a database that stores, name, email, uname, password, calories. I want to update the value of the calories column based on what the username is. When a new account is created the value of calories is set to default..
Here is my code I have made a start. I have made a class called database which stores all of my database functions..
The code:
SQLiteDatabase db;
public void
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "update tbltest set calories= "+c.getCalories()+" where uname= "+ c.getUname();
Cursor cursor = db.rawQuery(query , null);;
}
Offer any help on how i can approach this?
Try with this...
public void insertCalories(Intents c)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("calories", c.getCalories);
String selection = "where uname = ?";
String[] selectionArgs = new String[]{c.getUname()};
int result = db.update(
"tbltest",
values,
selection,
selectionArgs);
}
if result>0, then update is successful.
Put the values in the Contentvalues, you already created.
values.put (columnname, value);
then update the Database with the method update like this:
db.update ("tbltest", values, "WHERE uname = ?", new String []{c.getUname ()});
P.s. You should pass the constructor of Contentvalues the amount of values you want to update
I'm trying to add new values to my GridView, that are later passed to Cache and DataSet and underlying SQL Database.
Here is my code, but I can't figure out what to type on the line "dataRow["ID"]=" as you can see. Everything else works fine and the other values are added to the database if I just give "ID" any number that doesn't exist.
protected void insertStudent_Click(object sender, EventArgs e)
{
DataSet dataSet = (DataSet)Cache["DATASET"];
//DataRow dataRow = dataSet.Tables["Students"].Rows.Find(e.Keys["ID"]);
dataSet.Tables["Students"].PrimaryKey = new DataColumn[] { dataSet.Tables["Students"].Columns["ID"] };
DataRow dataRow = dataSet.Tables["Students"].NewRow();
dataRow["ID"] =
dataRow["FirstName"] = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
dataRow["LastName"] = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
dataRow["Gender"] = ((DropDownList)GridView1.FooterRow.FindControl("DropDownListGender")).SelectedValue;
dataRow["Course"] = ((DropDownList)GridView1.FooterRow.FindControl("DropDownListCourse")).SelectedValue;
dataRow["Grade"] = ((DropDownList)GridView1.FooterRow.FindControl("DropDownListGrade")).SelectedValue;
Cache.Insert("DATASET", dataSet, null, DateTime.Now.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);
dataSet.Tables["Students"].Rows.Add(dataRow);
GridView1.DataSource = (DataSet)Cache["DATASET"];
GridView1.DataBind();
}
As per Andrei in the comment above, set up your ID column in the table as:
CREATE TABLE sample( ID INT IDENTITY(1,1) NOT NULL,
FirstName VARCHAR(50) )) -- And your rest of the details
No need to add a value to ID, it will increment by itself. Insert other values and when you read from the database, you have ID column incremented.
P.S. Do not include ID column while inserting other values to the table.
Google 'SQL INCREMENT' for more information.
The answer to this question is to use AutoIncrement on the ID Column in your Cached DataSet. Then when you save to DB, the added rows will get their correct ID in the DB.
dataSet.Tables["Students"].Columns["ID"].AutoIncrement = true;
Can someone please let me know the issue with the below query? I am running on MS Access and its giving
Syntax error in query expression 'id = ##IDENTITY'
Code:
public DosageBO SaveDosage(DosageBO dosage)
{
try
{
using (IDbConnection connection = OpenConnection())
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("INSERT INTO dosage_master ( medicine_type, dosage, remarks, updateby, updatedate )");
sql.AppendLine("VALUES (#type, #dose, #remarks, #updateby, NOW());");
var parameters = new
{
type = dosage.MedicineType,
dose = dosage.Dosage,
remarks = dosage.Remarks,
updateby = Environment.UserName
};
connection.Execute(sql.ToString(), parameters);
return connection.Query<DosageBO>("SELECT medicine_type as MedicineType, dosage, remarks FROM dosage_master WHERE id = ##IDENTITY").FirstOrDefault();
}
}
catch
{
throw;
}
}
SELECT ##Identity is a specialized query. And ##Identity is only valid in that context. If you attempt to use ##Identity elsewhere, as in a WHERE clause, the db engine will throw an error.
You will have to retrieve the value from SELECT ##Identity, save it, and then use that saved value in your other query.
Remove the ) at the end
WHERE id = ##IDENTITY)
^---here
Are you inserting a row in this batch prior to the select query?
To my knowledge ##IDENTITY is only available directly after inserting a row causing an identity value to be generated i.e an insert to an autoincremental identity column.
Edit again:
Try enclosing it in a subquery e.g id = (SELECT ##IDENTITY)
I am new to NHibernate and I want to have a count of rows from database. Below is my code,
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
int count = template.Criteria.SetProjection(Projections.Count("ID"));
It gives me an error when I try to compile app that says
"Cannot implicitly convert type 'NHibernate.Criterion.DetachedCriteria' to 'int'"
I want to have a count of rows of the table hotel..
You want to use GetExecutableCriteria:
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
var count = DoCount(template.Criteria, session /* your session */);
public long DoCount(DetachedCriteria criteria, ISession session)
{
return Convert.ToInt64(criteria.GetExecutableCriteria(session)
.SetProjection(Projections.RowCountInt64())
.UniqueResult());
}
On a side note, you should take a look at using NHibernate.Linq:
var result = (from h in Session.Linq<Hotel>()
where h.CheckOutDate <= SelDate
where h.Canceled != true
select h).Count();
More information here.