I have a data base, this is in my proyect how a file localDB.db I want update some information of a table in this since my aplication`s code the method I use is the follow:
-(void)establecePerfil:(int)idPerfil{
while ([Utilidades consultaCargandoDatosDB]) {
[NSThread sleepForTimeInterval:1.0];
}
[Utilidades cargandoDatos:YES];
//perfil = [Perfil getInstance];
[self cargarBaseDeDatos];
NSLog(#"entre en establecer perfik");
sqlite3 *dataBase;
sqlite3_stmt *sentencia;
if(sqlite3_open([self.dataBasePath UTF8String], &dataBase)==SQLITE_OK){
NSLog(#"entre en establecer perfik 2");
NSString *sql = [NSString stringWithFormat:#"UPDATE perfiles SET \"seleccionado\"= 1, \"completado\"=0 WHERE \"id\"= %d", idPerfil];
if(sqlite3_prepare_v2(dataBase, [sql UTF8String], -1, &sentencia, NULL)==SQLITE_OK){
sqlite3_reset(sentencia);
if(sqlite3_step(sentencia)==SQLITE_OK){
NSLog(#"set profile OK");
}
else{
// NSAssert1(0, #"Error while selecting. '%s'", sqlite3_errmsg(dataBase));
NSLog( #"Save Error: %s", sqlite3_errmsg(dataBase) );
NSLog(#"%i", sqlite3_extended_errcode(dataBase));
NSLog(#"%i",sqlite3_errcode(dataBase));
}
}
sqlite3_finalize(sentencia);
}else{
NSLog(#"No se ha abierto la base de datos");
}
sqlite3_close(dataBase);
[Utilidades cargandoDatos:NO];
}
I think, I have the problem in sqlite3_step(sentencia) because code error that appear after of else condition is 101 referencing to SQLITE_DONE so I don`t know that means this.
The documentation says that SQLITE_DONE is correct (and SQLITE_OK would not be).
Related
i have a problem with my SQLite Database in QT5. I have table called "mytable" and im trying to save, change or load data there. The table looks like this (CODE):
"mytable" ("id" INTEGER PRIMARY KEY NOT NULL , "name" VARCHAR NOT NULL , "akcie" INTEGER NOT NULL )
Then im trying to work with this database like this (CODE):
void MainWindow::on_pushButton_save_clicked()
{
QString jmeno, IDcko, ak;
IDcko = ui->lineEdit_ID->text();
jmeno = ui->lineEdit_Name->text();
ak = ui->lineEdit_Akcie->text();
open_connection();
QSqlQuery query;
query.prepare("INSERT INTO mytable(id, name, akcie) VALUES(id= \'"+ IDcko +"\', name= \'"+ jmeno +"\', akcie= \'"+ ak +"\')");
if(query.exec())
{
QMessageBox::information(this, tr("SAVED"), tr("Some text."));
close_connection();
}
else
{
QMessageBox::critical(this, tr("NOT SAVED"), query.lastError().text());
qDebug() << query.lastError().text();
}
}
In the same file im opening connection like this (CODE):
bool MainWindow::open_connection()
{
QSqlDatabase database;
database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("..\\added\\test_table.sqlite");
if(!database.open())
{
qDebug() << "not opened connection";
return false;
}
else
{
qDebug() << "opened connection";
return true;
}
}
And im still getting error: "No query Unable to fetch row", i have been looking for the answer really hard but nothing worked. Could it be because of some includes or am I doing something wrong?
Thank you in advance for your help!
You are not preparing the query right. Use bindings like:
query.prepare("INSERT INTO mytable(id, name, akcie) VALUES(:id, :name, :akcie)");
query.bindValue(":id", IDcko);
query.bindValue(":name", jmeno);
query.bindValue(":akcie", ak);
You did not execute the query. You should use bindings like:
query.prepare("INSERT INTO mytable(id, name, akcie) VALUES(?, ?, ?)");
query.addBindValue(IDcko);
query.addBindValue(jmeno);
query.addBindValue(ak);
query.exec();
or, like #Miki mentioned, with the help of query.bindValue(":id", IDCko) function.
The last way will be to write the query text straightly (without the need to separately call query.exec():
query("INSERT INTO mytable(id, name, akcie) VALUES(id= \'"+ IDcko +"\', name= \'"+ jmeno +"\', akcie= \'"+ ak +"\')");
the code below is a cgi file and I am having problems displaying the image and style from an external css file. The code is in lines 18-28 and I'm not sure what I am doing wrong. I would appreciate any help.
#!/usr/bin/perl -w
use strict;
use DBI;
use CGI;
use CGI::Carp('fatalsToBrowser');
my $query = new CGI;
print $query->header();
my $my_database = "TrypSnoDB";
my $localhost = "localhost";
my $dsn = "DBI:mysql:$my_database:$localhost";
my $db_user_name = "adrian";
my $db_password = "temp_pass";
my $dbh = DBI->connect("DBI:mysql:database=TrypSnoDB;host=localhost;mysql_socket=/private/software/mysql/mysql.sock","adrian","temp_pass", {'RaiseError' => 1});
print "<html>\n";
print "<head>\n";
print "<title>Welcome to the T. Brucei snoRNA Database</title>\n";
print "<link type='text/css' rel='stylesheet' href='/public_html/style.css'>\n";
print "</head>\n";
print "<body>\n";
print "<h1>Trypanosomatid snoRNA Database</h1>\n";
print "<img class='my_images' src='/public_html/tb_pic1.png'>\n";
print "</body>\n";
print "</html>\n";
if ($query->param('submit1')){
my $orig_sno = $query->param('snorna1');
my $family = $query->param('family1');
my $query_type = $query->param('target_option1');
my $target = $query->param('target_name1');
if ($orig_sno eq "Trypanosoma brucei") {
$orig_sno = 1;
}
elsif ($orig_sno eq "Leishmania major") {
$orig_sno = 7;
}
elsif ($orig_sno eq "ALL") {
$orig_sno = "1 or ST.org_id=7";
}
if ($family eq "ALL") {
$family = "'C/D' or ST.family='H/ACA'";
}
else {
$family = "'$family'";
}
if ($target ne "ALL") {
$family = "$family and T.target_name='$target'";
}
my($db_query,$common_tar,$exp_ver_sno,$exp_ver_tar,$total);
$db_query = "SELECT ST.sno_name,T.target_name,T.location,T.base_pair,SM.annotated_seq FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and SM.mod_id=T.target_id and (ST.org_id=$orig_sno) and (ST.family=$family)";
$common_tar="and T.target_id in(SELECT T.target_id FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and SM.mod_id=T.target_id group by T.target_id having count(*)=2) order by T.location desc";
$exp_ver_sno="and ST.exper_ver='Y'";
$exp_ver_tar = "and T.exp_ver='Y'";
if ($query_type eq "snoRNAs with common targets") {
$db_query=$db_query.$common_tar;
}
elsif ($query_type eq "Experimentally verified snoRNAs") {
$db_query=$db_query.$exp_ver_sno;
}
elsif ($query_type eq "snoRNAs with experimentally verified targets") {
$db_query=$db_query.$exp_ver_tar;
}
elsif ($query_type eq "ALL"){
$db_query=$db_query;
}
my $sth = $dbh->prepare($db_query);
$sth->execute();
my$total = $sth->rows;
print "<table border=1>\n
<tr>
<th>snoRNA</th>\n
<th>Target Name</th>\n
<th>Target Location</th>\n
<th>Target Base Pair</th>\n
<th>Annotated Sequence</th>\n
</tr>\n";
while (my#row = $sth->fetchrow_array()){
my$sno_name = $row[0];
my$tar_name = $row[1];
my$tar_loc = $row[2];
my$tar_bp = $row[3];
my$annotated_seq = $row[4];
print "<tr>\n<td>$sno_name</td><td>$tar_name</td><td>$tar_loc</td><td>$tar_bp</td><td>$annotated_seq</td></tr>\n";
}
print "<tr>
<th>TOTAL</th>\n
<th>$total</th>\n
</tr>\n";
print "</table>";
}
Your problem is almost certainly that you have the wrong URL for the CSS file. You can confirm that by looking in the web server error log and seeing if there is a 404 record for the CSS request.
Unfortunately I can't tell you what the correct URL is as I have no idea how your web server is configured.
There are a couple of other issues that you might want to address though:
The HTML that you generate is invalid. You print the tags outside of the and tags. Printing raw HTML within your Perl program is a terrible idea - it's far too easy to make the kinds of errors that you have here. You would be far better advised to use a templating engine (I recommend the Template Toolkit).
Your database queries are prone to SQL injection attacks. Please switch to using bind variables before someone trashes your server.
this is in response to Dave Cross comment regarding the SQL statement building. To convert the statement build to use bindings appears to be fairly straightforward in order to prevent an SQL injection.
To use placeholder bindings I think the OP only needs to replace the variables $orig_sno and $family in the $db_query variable with the ? character. like so:
$db_query = "SELECT ST.sno_name,T.target_name,T.location,T.base_pair,SM.annotated_seq
FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and
SM.mod_id=T.target_id and (ST.org_id=?) and (ST.family=?)"; # one line
...
my $sth = $dbh->prepare($db_query);
$sth->execute($orig_sno, $family);
However as the $family variable is built possibly out of a previous conditional, a further variable $target is also in play.
if ($family eq "ALL") {
$family = "'C/D' or ST.family='H/ACA'";
}
else {
$family = "'$family'";
}
if ($target ne "ALL") {
$family = "$family and T.target_name='$target'";
}
Will the placeholder handle this interpolated variable? Or would the $target variable also require its own placeholder?
And is this all that would be required to do to deter would be SQL injection attacks in this case?
solved. If the $target variable did require its own place holder, a few adjustments to the conditionals would do the trick.
else {
$family = "'$family'";
}
# removed - if $target ne ALL conditonal
my($db_query,$common_tar,$exp_ver_sno,$exp_ver_tar,$total);
$db_query = "SELECT ... and (ST.org_id=?) and (ST.family=?)";
if ($target ne "ALL") {
$db_query =~ s/\)$//;
$db_query .= ' and T.target_name=?)';
}
$common_tar="and T.target_id ... ";
...
my $sth = $dbh->prepare($db_query);
if ($target ne 'ALL'){
$sth->execute($orig_sno, $family, $target);
else{
$sth->execute($orig_sno, $family);
}
NSString *cityInput = cityField.text;
NSString *code = #"";
NSString *query = #"SELECT code FROM country WHERE cityname = UPPER(?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String],-1, &statement, nil) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [cityInput UTF8String], -1, SQLITE_STATIC);
while(sqlite3_step(statement) == SQLITE_ROW) {
code = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
}
}
if(sqlite3_step(statement) != SQLITE_DONE){
NSLog(#"DB: query KO");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ALERT" message:#"City not found" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
return;
}
sqlite3_close(database);
Two questions:
1) for get single row i must use while loop?
2) if there isn't result in the query how alert "city not found"
Obviously you will get the last row,,
code
should be an array u might declare it like this
NSMutableArray *code=[NSMutableArray array];
then in the while loop use
[code addobject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
I hope this is clear enough:)
Using while gives you the last row and it is not needed. Add limit 1 clause to your query, or simply take the first row returned;
Decide whether to show alert by checking return code.
Maybe two answers,
1) No, just an if clause will do
2) Do an assignement and then run an if clause on it
int result = sqlite3_step(statement)
if (result == SQLITE_ROW){
//processline
}
else{
//show alert
}
My requirement is if the user click on update data with out changing any field on the form i would like to show as No changes made and if any changes i would like to update the data
I have written a Routine for updating data as follows
CREATE DEFINER=`root`#`%` PROCEDURE `uspEmployeeFaxDetailsUpdate`(_EmpID int(11),
_FaxNumberTypeID varchar(45),
_FaxNumber decimal(10,0),
_EndDate datetime)
BEGIN
declare p_ecount int;
set p_ecount= (select count(1) from tblemployeefaxdetails where
FaxNumberTypeID=_FaxNumberTypeID and
FaxNumber=_FaxNumber and
EndDate='9999-12-31');
if p_ecount=0 then
begin
update tblemployeefaxdetails
set
EndDate=_EndDate WHERE EmpID=_EmpID and EndDate="9999-12-31";
insert into tblemployeefaxdetails(EmpID,FaxNumberTypeID,FaxNumber,StartDate,EndDate) values
(_EmpID,_FaxNumberTypeID,_FaxNumber,curdate(),'9999-12-31');
end;
end if;
END
I am getting some time my required message but some time it is showing the update message
This is my code on update
oEmployeePersonalData.EmpID = EmpID;
oEmployeePersonalData.FaxNumberTypeID = ddlFaxTypeID.SelectedItem.Text;
oEmployeePersonalData.FaxNumber = Convert.ToInt64(txtFaxNumber.Text);
oEmployeePersonalData.EndDate = DateTime.Today.AddDays(-1);
if (oEmployeePersonalData.FaxDetailUpdate())
{
oMsg.Message = "Updated Sucessfully";
Label m_locallblMessage;
oMsg.AlertMessageBox(out m_locallblMessage);
Page.Controls.Add(m_locallblMessage);
}
else
{
oMsg.Message = "Not Sucessfully";
Label m_locallblMessage;
oMsg.AlertMessageBox(out m_locallblMessage);
Page.Controls.Add(m_locallblMessage);
}
Updated code
public bool FaxDetailUpdate()
{
m_bFlag = false;
try
{
m_oCmd = new MySqlCommand(StoredProcNames.tblEmployeeFaxdetails_uspEmployeeFaxdetailsUpdate, m_oConn);
m_oCmd.CommandType = CommandType.StoredProcedure;
m_oCmd.Parameters.AddWithValue("_EmpID", EmpID);
m_oCmd.Parameters.AddWithValue("_FaxNumberTypeID", FaxNumberTypeID);
m_oCmd.Parameters.AddWithValue("_FaxNumber", FaxNumber);
m_oCmd.Parameters.AddWithValue("_EndDate", EndDate);
if (m_oConn.State == ConnectionState.Closed)
{
m_oConn.Open();
}
if ((m_oCmd.ExecuteNonQuery()) > 0)
{
this.m_bFlag = true;
}
}
catch (MySqlException oSqlEx)
{
m_sbErrMsg.Length = 0;
m_sbErrMsg = Utilities.SqlErrorMessage(oSqlEx);
//DB write the Error Log
m_oErrlog.Add(m_sbErrMsg.ToString(), DateTime.Now);
}
catch (Exception oEx)
{
m_sbErrMsg = Utilities.ErrorMessage(oEx);
//DB write the Error Log
m_oErrlog.Add(m_sbErrMsg.ToString(), DateTime.Now);
}
finally
{
m_oConn.Close();
}
return this.m_bFlag;
}
I am not getting any error but i would like to be done as per i said
Can any one tell what changes i have to made in this
I do not really understand the routine, what the magic date 9999-12-31 represents, and why a new record is inserted every time, instead of updating the old one.
What you can do, is have the routine return a indicator if the row was changed or not, returning the value of p_ecount through a OUT parameter.
For more information on how to use OUT parameters using the .net MySql client see http://dev.mysql.com/doc/refman/5.0/en/connector-net-programming-stored.html
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?
NSString *ans = #"";
for (id obj in anExpression)
{
if ([obj isKindOfClass:[NSString class]])
[ans stringByAppendingString:(NSString *)obj];
if ([obj isKindOfClass:[NSNumber class]])
[ans stringByAppendingString:(NSString *)[obj stringValue]];
NSLog(#"String so far: %# ", ans);
}
I think you mean
ans = [ans stringByAppendingString:(NSString *)obj];
not just
[ans stringByAppendingString:(NSString *)obj];
NSStrings are immutable -- you can't append to them. -stringByAppendingString: returns a new string (which you could then assign to ans).
Alternatively, you might use an NSMutableString and the -appendString: method.
Hey, sorry for the bad coding format, posting it again ...
NSString *ans = #"";
for (id obj in anExpression)
{
if ([obj isKindOfClass:[NSString class]])
[ans stringByAppendingString:(NSString *)obj];
if ([obj isKindOfClass:[NSNumber class]])
[ans stringByAppendingString:(NSString *)[obj stringValue]];
NSLog(#"String so far: %# ", ans);
}
[ans autorelease];
NSLog(#"final string is: %# ", ans);
return ans;
the method stringByAppendingString: returns a new string made by appending the given string to the receiver.
so you want ans = [ans stringByAppendingString:obj];