I'm building a simple app which requires two tables in a database. To create the tables and the database I use the following syntax->
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sqlite_api.dart';
class DBHelper {
static Future<Database> database() async {
final dbPath = await sql.getDatabasesPath();
return sql.openDatabase(path.join(dbPath, 'users.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE user_profile(id TEXT PRIMARY KEY, name TEXT, address TEXT,mobileno TEXT,dob TEXT);CREATE TABLE user_transactions(id TEXT PRIMARY KEY, date TEXT, amount TEXT,cart TEXT)');
}, version: 1);
}
When I excuete a method to add data to the the table 'user_transactions' it gives me an error as 'E/SQLiteLog(24687): (1) no such table: user_transactions
'. The fetching and adding data to user_profile works perfectly fine. I also executed the sql query in db browser for sqlite and no error was found there.I also tried uninstalling the app and installing it again.Please help
I think the best solution to create multiple tables in SQLite is this instead of yours:
class DBHelper {
Future<Database> database() async {
return openDatabase(
join(await getDatabasesPath(), 'users.db'),
onCreate: (db, version) async {
await db.execute(
"CREATE TABLE user_profile(id TEXT PRIMARY KEY, name TEXT, address TEXT,mobileno TEXT,dob TEXT)");
await db.execute(
"CREATE TABLE user_transactions(id TEXT PRIMARY KEY, date TEXT, amount TEXT,cart TEXT)");
return db;
},
version: 1,
);}
Just Uninstall the app and re-install the app. Why it works ?
You might already have users.db db created for the app and onCreate is executed when db is created for the first time, so uninstalling and re-installing the app would solve the problem.
Related
I'm developing my first Shopware 6 admin plugin, for which is required to extend one of the existing Shopware plugins - Custom products.
I want to add a relation between already existing entities - TemplateExclusion and TemplateOptionDefinition. When I select from the UI my options, TemplateExclusion entity its getting saved in the database, without any problems.
When I save the Template entity (parent of TemplateExclusion), my "excluded_option_id" its getting overwritten with the 1st possible option from TemplateOptionDefinition entities.
I have notice that this is happening on "mergeVersion". Also when I try to save the Template entity with debug mode enabled and profiler, I'm getting an error during saving, that "excludedOptionId" is blank when merging, which is not true.
Error in profiler
Following the documentation I made first the migration:
class Migration1643023742TemplateExclusionRelation extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1643023742;
}
public function update(Connection $connection): void
{
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD COLUMN `excluded_option_id` BINARY(16) AFTER `template_version_id`;');
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD COLUMN `excluded_option_version_id` BINARY(16) AFTER `excluded_option_id`;');
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD CONSTRAINT `fk.swag_cupr_template_exclusion.excluded_option_id` FOREIGN KEY (`excluded_option_id`, `excluded_option_version_id`)
REFERENCES `swag_customized_products_template_option` (`id`, `version_id`) ON DELETE CASCADE ON UPDATE CASCADE;');
}
then I made an entity extension, where to define the new fields.
class TemplateExclusionExtension extends EntityExtension
{
public function extendFields(FieldCollection $collection): void
{
$collection->add(
(new FkField('excluded_option_id', 'excludedOptionId', TemplateOptionDefinition::class))
->addFlags(new Required(), new ApiAware())
);
$collection->add(
(new ManyToOneAssociationField('excludedOption', 'excluded_option_id', TemplateOptionDefinition::class))
->addFlags(new ApiAware())
);
$collection->add(
(new ReferenceVersionField(TemplateOptionDefinition::class, 'excluded_option_version_id'))
->addFlags(new Required(), new ApiAware()),
);
}
public function getDefinitionClass(): string
{
return TemplateExclusionDefinition::class;
}
}
Solved:
It was wrong definition from my side:
public function extendFields(FieldCollection $collection): void
{
$collection->add(
(new FkField('excluded_option_id', 'excludedOptionId', TemplateOptionDefinition::class))
->addFlags(new Required(), new ApiAware())
);
$collection->add(
(new OneToOneAssociationField(
EasyExtendCustomizedProducts::TEMPLATE_EXCLUSION_EXCLUDED_OPTION_EXTENSION,
'excluded_option_id',
'id',
TemplateOptionDefinition::class,
false
))->addFlags(new CascadeDelete(), new ApiAware())
);
}
public function getDefinitionClass(): string
{
return TemplateExclusionDefinition::class;
}
If I'm not mistaken the issue was the missing CascadeDelete delete flag.
To versionize the entity it is first fetched including its associated data and is then persisted with new primary keys, so basically it gets cloned. However not all associations are taken into account when fetching the data to be cloned. You can find the responsible code here, where the affected associations get filtered by the existence of the CascadeDelete flag. If they miss the flag they will be ignored for creating the cloned version. This behavior still needs to be documented more prominently.
So I have a very simple table I made in SQL using h2
CREATE TABLE USERS(
username varchar(255) NOT NULL,
password varchar(255),
);
I'm trying to use javalite to add an entry to it so I made this following the instructions on the site.
package DBTEST;
import org.javalite.activejdbc.Base;
public class makeDB {
public static void main(String[] args) {
Base.open("org.h2.Driver", "jdbc:h2:./test", "sa", "");
User e = new User();
e.set("username", "John");
e.set("password", "Doe");
e.saveIt();
User.findAll().dump();
Base.close();
}
}
I have a class Users for this table
package DBTEST;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
#Table("USERS")
public class User extends Model {
}
I keep getting this exception
Exception in thread "main" org.javalite.activejdbc.DBException: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "USERS" not found; SQL statement:
Can anyone help? I have no idea why this is happening
First, your SQL has an extra comma in "CREATE USERS" statement. The errors says: "able "USERS" not found" - this mean you simply do not have a table!
Second, the table definition is missing an id, please see https://javalite.io/surrogate_primary_keys
Third, I created a simple example project and added your code there. It is working as expected. The project can be found here: https://github.com/javalite/h2-example
The output from running this program looks like this:
Model: activejdbc.examples.simple.User, table: 'users', attributes: {ID=1, PASSWORD=Doe, USERNAME=John}
which is exactly as expected.
Additionally, the #Table annotation is not necessary: https://javalite.io/english_inflections
I'm having difficult coming up with the best possible way of storing todo list items in the backend. I was told that storing array and object in the backend was not a good idea. I'm trying to clone a google keep inspired web app.
Some context: as soon as the user submits their todo list, it will make an axios call to the backend that will iterate through an array of todo list items and save them individually to the backend.
Which inspired me with this current set up.
CREATE TABLE TODO (
ID SERIAL PRIMARY KEY,
title VARCHAR,
user_id INTEGER REFERENCES users(ID));
CREATE TABLE TODO_ITEM (
ID SERIAL PRIMARY KEY,
item VARCHAR,
complete BOOLEAN,
todo_list_id INTEGER REFERENCES TODO(id));
My frontend call to the backend looks like this
toDoArray.map(ele => {
axios.post('users/postToDoListItems', {
item: ele,
complete: false,
todo_list_id: ?
})
})
axios.post('users/postToDoList', {
title: title,
toDoList: toDoList
})
}
The TODO_ITEM table I would like to to reference my TODO table so that when it's called to the frontend and grouped with the correct table.
With my current setup, is it possible to pass the reference (TODO)ID to TODO_ITEM table?
so aaaww i think you made some little mistakes i dont know how you query on your back-end but you must notice that before making your tables you must make a connection to your db soo i think it's not back to check this
or if you did it before plz complete your info about your problem , but the right thing for making queries is this :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
and for query from front-end you should do this :
<< fron-end >>
axios.post('users/postToDoListItems', {
item: ele,
complete: false,
todo_list_id: 1
})
<< back-end >>
route : postToDoListItems
connection.query(`SET complete = ${req.body.complete} FROM todo WHERE id =${req.body.id}`, function (error, results, fields) {
if (error) throw error;
res.json({results,fields})
});
I am learning MVC2 and I am trying to create a data request management system. Somewhat like a ticketing system. A quick question, in my mvc controller class I have a post-create
[HttpPost]
public ActionResult Create(Request request)
{
if (ModelState.IsValid)
{
try
{
// TODO: Add insert logic here
var db = new DB();
db.Requests.InsertOnSubmit(request);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View(request);
}
}
else
{
return View(request);
}
}
Ok, this is extremely simple enough, well I add my view and once I create a row I get the 0 first in my Primary Key row. Then it will not increment anymore, I goto add another row and the catch returns me to the same view I am on. It seems that the primary key int id is not incrementing.
How do you auto increment the id (type int) here? I am a bit confused why MVC isn't handling this since it is the primary key type int. It will only make the first row with the id = 0 and that's all.
Your ID column needs to be set as an Identity column in the table in SQL server.
Also you should create your DB data context in a using:
using(var db = new DB())
{
db.Requests.InsertOnSubmit(request);
db.SubmitChanges();
return RedirectToAction("Index");
}
Otherwise you're spilling connections all over the place; and creating more memory leaks than an early build of windows (well, depending on your traffic ;) )
I'm using Zend Framework version 1.7.8.
I am trying to create a class that extends from Zend_Db_Table_Abstract:
class My_Model_Table extends Zend_Db_Table_Abstract {
public function __construct($tableName) {
parent::__construct(array('name' => $tableName, 'primary' => 'dummy', 'db' => Zend_Registry::get('dbAdapter')));
}
}
However, when I try to fetch from this table:
$table = new My_Model_Table('dual');
Zend_Debug::dump($table->fetchAll());
I am getting this exception:
Primary key column(s) (dummy) are not columns in this table (DUMMY)
For those of you not familiar with Oracle, the DUAL table is a standard Oracle table which has only one column: DUMMY. From what I can see in the error message, ZF is trying to fetch from the "DUMMY" table which doesn't exist. Am I right? What am I doing wrong?
Thanks!
Have you tried:
Class VCCE_Model_Table extends Zend_Db_Table_Abstract {
protected $_name = 'DUAL';
}
$table = new VCCE_Model_Table();
Zend_Debug::dump($table->fetchAll());
Note: in your example you use two different names for your table VCCE_Model_Table and My_Model_Table.
Did you check the configuration settings for dbAdapter?