i want to enter data in a complete column without according to row data - android-sqlite

i'm using sq lite database in android
i already have data in two columns i want to change data in column 2 without condition of where
where ever i searched where condition is used
this is how i stored
public boolean updateData(String name, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2,pass);
db.update(TABLE_NAME,contentValues, col1+" =?", new String[]{name});
return true;
}

Pass null for the 3d and 4th arguments:
public boolean updateData(String pass) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, pass);
db.update(TABLE_NAME, contentValues, null, null);
db.close();
return true;
}
I guess you don't need the parameter name since there is no WHERE clause, so I removed it.

Related

What is the fastest way to insert data using Spring Boot jdbc?

I have a Spring Boot application where I batch insert hundreds of thousands of rows across two tables where I insert one row in one of the tables, return the id and use it to insert one row in the other table. As it is right now it's simply not fast enough. I would like to know what is the fastest way to do it. Here is my code:
private void insertData(DataList request, long personId, String tableName) {
try {
String sql = """
WITH inserted AS
(INSERT INTO user_%s (username, password, email, phone, person_id) VALUES (?,?,?,?,?) RETURNING user_id)
INSERT INTO info_%s (user_id, info, full_text_search) VALUES ((SELECT user_id FROM inserted), ?, to_tsvector(?));
""".formatted(tableName, tableName);
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public void setValues(#Nonnull PreparedStatement ps, int i) throws SQLException {
Data data = request.getData(i);
ps.setTimestamp(1, data.getUsername());
ps.setLong(2, data.getPassword());
ps.setInt(3, data.getEmail());
ps.setInt(4, data.getPhone());
ps.setString(5, data.getpersonId());
ps.setString(6, data.getInfo());
ps.setString(7, data.getInfo());
}
#Override
public int getBatchSize() {
return request.getDataCount();
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
I'm using PostgreSQL as my database.

C# programming with window forms

private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
When i run this code then my whole database table is updated with the current values and i can't understand the problem
"where id = ID" condition is always true so all records are affected. You need to actually set a value for "ID". Perhaps you need to write
"where id =" + ID.ToString()

Updating single row in SQLite Android Studio

So I'm trying to update one row of my sql database with this following method
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
However, whenever the function is called, it updates all the rows. I've tried to change the values within the "update" method called but I haven't been able to make it work
There is nothing intrinsically wrong with the code that you have shown. The example below, which utilises your exact code that you have shown, works.
As such your issue is either with other unprovided code or with the method you are using to determine that no data has been updated.
For this test the following was the code for the class that is subclass of SQLiteOpenHelper, in this case ServiceDBHelper.java :-
public class ServiceDBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "service.db";
public static final int DBVERSION = 1;
public static final String TABLE_SERVICE = "service";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_RATE = "rate";
public ServiceDBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_SERVICE + "(" +
COLUMN_NAME + " TEXT PRIMARY KEY, " +
COLUMN_RATE + " TEXT" +
")";
db.execSQL(crt_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertService(String name, String price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME,name);
cv.put(COLUMN_RATE,price);
return db.insert(TABLE_SERVICE,null,cv);
}
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
public void logService(String description) {
String TAG = "LOGSERVICE";
Log.d(TAG,"Logging information for the Service Table for " + description);
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_SERVICE,null,null,null,null,null,null);
Log.d(TAG,"Number of rows in the " + TABLE_SERVICE + " table is " + String.valueOf(csr.getCount()));
while (csr.moveToNext()) {
Log.d(TAG,
"Column " + COLUMN_NAME + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_NAME)) +
". Column " + COLUMN_RATE + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_RATE))
);
}
csr.close();
}
}
As you can see the modiService method is as per you code.
Other code has been added to :-
Create the table (named service) when the database is created.
Insert rows into the table to add some test data.
Write to data from the table to the log.
The following is the code used in an Activity to
- insert some rows,
- display the rows
- update (modify a row)
- display the rows
The code used in MainActivity.java was :-
public class MainActivity extends AppCompatActivity {
ServiceDBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new ServiceDBHelper(this);
mDBHlpr.insertService("Fred","125.45");
mDBHlpr.insertService("Mary","99.75");
mDBHlpr.insertService("Harry","245.34");
mDBHlpr.logService("After initial inserts");
mDBHlpr.modiService("Mary","99.75","Susan","333.33");
mDBHlpr.logService("After Updating Mary to Susan");
}
}
The relevant output in the Log was :-
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After initial inserts
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Mary. Column rate has a value of 99.75
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After Updating Mary to Susan
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Susan. Column rate has a value of 333.33
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
As can be seen the row Mary 99.75 has been changed using the modiService method to Susan 333.33.

Change Crystal Reports DataSource From MSACCESS to SQLSERVER at runtime

I have a winforms application that is connecting to an MSACCESS Database located on a network. I am very keen to change the underlying database to sqlserver database on our local server. I am able to convert the database and get the application running (all table names, fields etc are preserved).
The application has over 300 crystal reports, which are configured to connect to the access datasource. I really dont want to have to manually reconfigure every report... so I am looking for a way to change the datasource at runtime
thanks for the assist, this solution seems to work for me though:
private void getConnectionInfo(string serverName, string databaseName, string userID, string password)
{
connectionInfo.ServerName = serverName;
connectionInfo.DatabaseName = databaseName;
connectionInfo.UserID = userID;
connectionInfo.Password = password;
}
private TableLogOnInfo GetSQLTableLogOnInfo(string serverName, string databaseName, string userID, string password)
{
CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag connectionAttributes = new CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag();
connectionAttributes.EnsureCapacity(11);
connectionAttributes.Add("Connect Timeout", "15");
connectionAttributes.Add("Data Source", serverName);
connectionAttributes.Add("General Timeout", "0");
connectionAttributes.Add("Initial Catalog", databaseName);
connectionAttributes.Add("Integrated Security", false);
connectionAttributes.Add("Locale Identifier", "1033");
connectionAttributes.Add("OLE DB Services", "-5");
connectionAttributes.Add("Provider", "SQLOLEDB");
connectionAttributes.Add("Tag with column collation when possible", "0");
connectionAttributes.Add("Use DSN Default Properties", false);
connectionAttributes.Add("Use Encryption for Data", "0");
DbConnectionAttributes attributes = new DbConnectionAttributes();
attributes.Collection.Add(new NameValuePair2("Database DLL", "crdb_ado.dll"));
attributes.Collection.Add(new NameValuePair2("QE_DatabaseName", databaseName));
attributes.Collection.Add(new NameValuePair2("QE_DatabaseType", "OLE DB (ADO)"));
attributes.Collection.Add(new NameValuePair2("QE_LogonProperties", connectionAttributes));
attributes.Collection.Add(new NameValuePair2("QE_ServerDescription", serverName));
attributes.Collection.Add(new NameValuePair2("SSO Enabled", false));
getConnectionInfo(serverName, databaseName, userID, password);
connectionInfo.Attributes = attributes;
connectionInfo.Type = ConnectionInfoType.SQL;
TableLogOnInfo tableLogOnInfo = new TableLogOnInfo();
tableLogOnInfo.ConnectionInfo = connectionInfo;
return tableLogOnInfo;
}
public ReportDocument GenerateReport(string reportPath, string report, string folder, List<ReportParameters> parameters)
{
ReportDocument crReport = new ReportDocument();
TableLogOnInfo crTableLogoninfo = new TableLogOnInfo();
Tables crTables;
string path = reportPath + folder;
crReport.Load(path + report);
crTables = crReport.Database.Tables;
TableLogOnInfo tableLogonInfo = this.GetSQLTableLogOnInfo(this.serverName, this.databaseName, this.userName, this.password );
foreach (Table table in crTables)
{
table.LogOnInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(table.LogOnInfo);
}
foreach (ReportDocument subrep in crReport.Subreports)
{
foreach (Table table in subrep.Database.Tables)
{
table.LogOnInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(table.LogOnInfo);
}
}
crReport.Refresh();
foreach (ReportParameters r in parameters)
crReport.SetParameterValue(r.parameter, r.value);
return crReport;
}

Do I really have to update every property individually with Entity Framework?

I have an update method in my Web API repository that looks like this (in EF Core):
public async Task<Employee> Update(Employee emp)
{
Employee employee = await
_context.Employees.SingleOrDefaultAsync(e => e.ID == emp.ID);
if (employee == null)
{
return null;
}
employee.FirstName = emp.FirstName;
employee.LastName = emp.LastName;
employee.Supervisor = emp.Supervisor;
employee.OfficeBureau = emp.OfficeBureau;
employee.Notes = emp.Notes;
await _context.SaveChangesAsync();
return employee;
}
It works well enough. But do we really have to do this?
I want to do something more like this and update all entity properties in one shot:
public async Task<Employee> Update(Employee emp)
{
Employee employee = await
_context.Employees.SingleOrDefaultAsync(e => e.ID == emp.ID);
if (employee == null)
{
return null;
}
employee = emp;
_context.Update(employee);
await _context.SaveChangesAsync();
return employee;
}
I shouldn't even need this:
employee = emp;
All I should need is this:
_context.Update(emp);
So EF should say, hey, I need to update an Employee object and I know which one it is by the ID of emp you passed me on update.
But I just can't get it to work.
Does anyone know how to do this or am I really supposed to do it like in the first option?
The answer below from Dmitry is not working.
If I put a break point here:
Employee employee = await
_context.Employees.SingleOrDefaultAsync(e => e.ID == emp.ID);
and then try and step though, execution seems to get swallowed up on this line:
_context.Entry(emp).State = EntityState.Modified;
and then this is the response returned:
{}
and the employee in the Database is unchanged.
Also tried this:
public async Task<Employee> Update(Employee emp)
{
Employee employee = await
_context.Employees.SingleOrDefaultAsync(e => e.ID == emp.ID);
if (employee == null)
{
return null;
}
EntityEntry<Employee> entity = _context.Employees.Attach(emp);
entity.State = EntityState.Modified;
_context.Employees.Update(emp);
await _context.SaveChangesAsync();
return employee;
}
But same thing.
Execution gets swallowed up here:
EntityEntry<Employee> entity = _context.Employees.Attach(emp);
Where is the execution going?
Hard to tell with async sometimes.
I got it to work once like this.
Funny, I got to work right off the bat when I put it in a try/catch.
public async Task<Employee> Update(Employee emp)
{
Employee employee = await
_context.Employees.SingleOrDefaultAsync(e => e.ID == emp.ID);
if (employee == null)
{
return null;
}
try
{
_context.Employees.Update(emp);
}
catch(Exception ex)
{
throw ex;
}
await _context.SaveChangesAsync();
return emp;
}
But it only worked once.
Now it keeps throwing this exception.
{System.InvalidOperationException: The instance of entity type 'Employee' cannot be tracked because another instance of this type with the same key
is already being tracked.
When adding new entities,
for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type).
If you are explicitly setting key values for new entities,
ensure they do not collide with existing entities or temporary values generated for other new entities.
"When attaching existing entities,
ensure that only one entity instance with a given key value is attached to the context.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func2 handleNode)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState) at Lerd.Models.Concrete.EmployeeRepository.d__4.MoveNext()}"
How do I get rid of this so dbContext.Update works everytime?
public async Task<Employee> Update(Employee emp)
{
_context.Entry(emp).State = EntityState.Modified;
await _context.SaveChangesAsync();
return employee;
}
I had to change my Repo to be Scoped rather than singleton:
From
services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
to:
services.AddScoped<IEmployeeRepository, EmployeeRepository>();