So I want to create a database for Users and insert values into the fields using variable. Initially I tried using it calling the do function, but it wasn't reading the variables properly so I decided to just use prepare and execute separately. This is my code:
$dbh->do("DROP TABLE IF EXISTS Users");
$dbh->do("CREATE TABLE Users(
zid TEXT,
Name TEXT,
Email TEXT,
password TEXT,
Mates TEXT,
Program TEXT,
Courses TEXT,
Suburb TEXT,
Birthday TEXT)");
$zid = "z33432523";
$name = "John Doe";
$email = "email#gmail.com";
$password = "alien";
$mates = "z3459148 z3458291";
$program = "";
$courses = "";
$suburb = "";
$birthday = "13/5/1992";
$sth = $dbh->prepare('INSERT INTO Users VALUES (?, ?, ?, ?, ?. ?, ?, ?, ?)');
$sth->execute($zid, $name, $email, $password, $mates, $program, $courses, $suburb, $birthday);
$dbh->disconnect();
However, if I try running this code I get the following error:
DBD::SQLite::db prepare failed: near ".": syntax error at ./dbm.pl line 35.
I'm not sure exactly what the problem is?
near ".": syntax error
INSERT INTO Users VALUES (?, ?, ?, ?, ?. ?, ?, ?, ?)
^
Related
I am trying to insert a new note into a database with the following flutter code. final noteId = await db.insert(noteTable, { userIDColumn: owner.id, textColumn: text, isSyncedWithCloudColumn: 1, });
I get the following exception Exception has occurred. SqfliteDatabaseException (DatabaseException(NOT NULL constraint failed: note.id (code 1299 SQLITE_CONSTRAINT_NOTNULL)) sql 'INSERT INTO note (user_id, text, is_synced_with_cloud) VALUES (?, ?, ?)' args [1, , 1])
I tried the code described above and got the exception instead of a successful result.
I didn't want to post this but last resort.
PHP with MS SQL Server 2008 and I'm getting an error of: [SQLSTATE[07002]: [Microsoft][ODBC Driver 11 for SQL Server]COUNT field incorrect or syntax error
Here is my code:
$server_name = 'sqlserver';
$user = 'user';
$passwd = 'pass';
$sqlString = "INSERT INTO dbo.tbl (UniqID, rideid, stopRatingId, category, ddescription, rating, createdDate) VALUES (?, ?, ?, ?, ?, ?, ?)";
$conn = new PDO("sqlsrv:Server=$server_name;Database=db;ConnectionPooling=0", $user, $passwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($sqlString);
$sqlVals = "'1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21'";
$stmt->execute(array($sqlVals));
The array shows:
print_r(array($sqlVals));
Array ( [0] => '1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21' )
when I try this, the insert is successful without error:
$stmt->execute(array('1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21'));
Not sure how to correct - any help is much appreciated!
In First example $sqlVals is treated as 1 string value not distinct values
so you can try this
$sqlVals = array('1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21');
$stmt->execute($sqlVals);
PreparedStatement pstmt = conn
.prepareStatement("INSERT INTO discussion(section_id, weekday, room, mandatory, starttime,endtime) VALUES ( ?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, Integer.parseInt(request.getParameter("SECTION_ID")));
pstmt.setString(2, request.getParameter("WEEKDAY"));
pstmt.setString(3, request.getParameter("ROOM"));
pstmt.setString(4, request.getParameter("MANDATORY"));
String TIME_FORMAT = "HH:mm";
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT,
Locale.getDefault());
out.println("Items: " + request.getParameter("starttime"));
out.println("Items: " + request.getParameter("WEEKDAY"));
pstmt.setTime(5,
new Time(timeFormat.parse(request.getParameter("starttime"))
.getTime()));
pstmt.setTime(6,
new Time(timeFormat.parse(request.getParameter("endtime"))
.getTime()));
pstmt.executeUpdate();
I use out.print to test. find out that getparameter works not right. It can give me the weekday data but cannot give me starttime data. The database give starttime time type
I have a class mapped like the following:
public class FooMap : ClassMap<Foo>
{
public FooMap()
{
Table("Foo");
LazyLoad();
CompositeId().KeyProperty(x => x.ID,
kp => kp.ColumnName("Id")
.Type(typeof(long)))
.KeyProperty(x => x.ValidFrom);
}
}
On the MSSQL side, Id is identity column and the table's PK is composed of Id and ValidFrom.
Here's the code I use to save:
ISession session = SessionService.GetSession();
new SqlCommand("SET IDENTITY_INSERT Foo ON",
session.Connection as SqlConnection)
.ExecuteNonQuery();
try
{
// performs various versioning checks,
// then saves using transaction.
// The session is the same as above
GenericDataService.Save(myFoo);
}
finally
{
new SqlCommand("SET IDENTITY_INSERT Foo OFF",
session.Connection as SqlConnection)
.ExecuteNonQuery();
}
Although I set Identity_Insert to ON, I get the following exception (when keeping ID and setting new ValidFrom):
Cannot insert explicit value for identity column in table 'Foo' when IDENTITY_INSERT is set to OFF.
This is the SQL executed:
INSERT INTO Foo (C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, Id, ValidFrom)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Can anyone explain why I still get that exception?
If the problem has to do with separate transactions like Nathan Fisher suggested, then NHibernate's ITransaction.Enlist(IDbCommand) method should fix it. Try something like this:
using (var trx = session.BeginTransaction())
{
ExecuteInNHTransaction(session, "SET IDENTITY_INSERT Foo ON");
session.Save(myFoo);
ExecuteInNHTransaction(session, "SET IDENTITY_INSERT Foo OFF");
trx.Commit();
}
private static void ExecuteInNHTransaction(ISession session, string commandText)
{
var command = new SqlCommand(commandText,
(SqlConnection) session.Connection);
session.Transaction.Enlist(command);
command.ExecuteNonQuery();
}
I want to do a simple WebOS Mojo app that adds dates to a database, but before that it needs to check few conditions by interrogating the database. Given the asynchronous mode of accessing the database in WebOS I'm wondering what is the most efficient and short way of writing such code.
For example I need to make sure the new date is not already in the database. Then I need to get the closest date so that I can compute the difference in days and throw an error if the difference is too small. Then I need to insert the new date and then compute an average.
This would be easy to do in a synchronous way of accessing the db, but I don't really like the idea of writing parts of the code in multiple success handlers of the different sql statements executed. Is there a more elegant solution?
You can use inline callbacks to the HTML 5 relational database functions:
function createProject(project, onSuccess) {
if (project.projectId)
throw new StorageError("project already exists");
if (project.path)
throw new StorageError("project already has a path");
project.projectId = ++Tracker.maxLocalId * 4096;
project.path = calcNextProjectPath();
project.normalize();
Tracker.db.transaction(
function (transaction) {
transaction.executeSql(
"INSERT OR ROLLBACK INTO item (dbId, path, hasChildren, kind, summaryText, place, work, responsible, responsibleClass) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
[project.projectId, project.path, project.hasChildren, project.kind, project.title, project.place, project.work, project.responsible, project.responsibleClass],
function (transaction, resultSet) {
Mojo.Log.info("DB: inserted new project item", resultSet.insertId, project.title);
transaction.executeSql(
"INSERT OR ROLLBACK INTO project (projectId, accountId, title, backendKind, backendStatus, backendLastChanged, lastSuccessfulDown) \
VALUES (?, ?, ?, ?, ?, ?, ?)",
[project.projectId, project.accountId, project.title, project.backendKind, project.backendStatus, project.backendLastChanged, project.lastSuccessfulDown],
function (transaction, resultSet) {
Warn.logInfo("created new project", "projectId=" + resultSet.insertId, project.title);
if (onSuccess)
onSuccess();
},
function (transaction, sqlError) {
Warn.bannerError("create", $L("Quit and reset your phone."), "project row insertion failed: ", sqlError.message, sqlError.code, project);
return true; // abort whole transaction
}
);
},
function (transaction, sqlError) { // failure of insert project item
if (sqlError.code === 1 && sqlError.message === "constraint failed" && Mojo.appInfo.id !== "com.outlinetracker.outlinetracker") {
upgradeAlert(true);
} else {
Warn.bannerError("create", $L("Quit and reset your phone."), "project item insertion failed: ", sqlError.message, sqlError.code);
}
return true; // abort whole transaction
}
);
}, // end transaction function
function (sqlError) { // seems to only be called for exceptions in callbacks
Warn.logError($L("Quit and reset your phone."), "transaction 'insert project' failed", sqlError.message, sqlError.code);
}
); // end transaction call
}