file is encrypted or is not a database , QT - database

Sorry for posting this even though there're a few posts about this , but they're not helping.
I'm using sqlite with QT , I wanted to do a simple query but it gives me this error:
file is encrypted or is not a database Unable to execute statement
Some posts' comments say that the DB may be corrupt, I used another program and created a test table from scratch and still has the same problem, this is the code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("AdmissionTestDB.sql");
db.open();
if(db.isOpen())
{
QSqlQuery q = db.exec("SELECT * FROM USERS");
if(!q.lastError().isValid())
{
qDebug()<<"works!";
while(q.next())
{
qDebug()<<q.value(8).toString();
}
}
else
qDebug()<<"---db failed to open! , error: "<<q.lastError().text();
db.close();
return true;
}
qDebug()<<"db failed to open! , error: "<<db.lastError().text();
return false;
More Information hopefully it would help solving this:
1- I'm using SQLITE 3
2- The problem happens when I use QSqlQuery q = db.exec("SELECT * FROM USERS"); so the DB actually opens!
3- I used two GUI programs to create the DB one of them is the latest version of SQLiteStudio which is version 3.0.4

Related

check in java netbeans if a database exists in sql server

I work with sql server as database in Java NetBeans and I want to create a database from Java, before doing this I need to check if it exists or not, I know that the sql syntax is large different from MySQL syntax so at the begining I did this sql syntax:
CREATE DATABASE IF NOT EXISTS
But it returns error so please can you tell how to check if it exist in this case it will not be created and if not exists how to create one. THANK YOU
One more way is to use DB_ID:
IF DB_ID(N'YourDBName') IS NULL
CREATE DATABASE YourDBName ....;
Returns the database identification (ID) number.
try {
String sql = "SELECT * FROM master.dbo.sysdatabases WHERE name = '"+base+"'";
pstt=conn.prepareStatement(sql);
rs = pstt.executeQuery();
if (rs.next()){
System.out.println("Database exist");
}
else{
String sqll = "CREATE DATABASE "+base;
pstt=conn.prepareStatement(sqll);
pstt.executeUpdate();
}
}
catch(Exception e){
}
i've tried this and it works fine with me, any way thanks for your reply

QSqlQuery does not work

I try to add to my database a row but it does not work.
My database is host by alwaysdata, I use Qt Creator to develop my program (which print no error) and MySql for viewing the database
via MySql Query Browser I entered :
INSERT INTO `mmr` VALUES (NULL,'musictest','albumtest','timetest','datetest');
it works
but in my program that code does not work :
void MainWindow::b_clicked(){
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("mysql1.alwaysdata.com");
db.setDatabaseName("mymusicrecognition_mmr");
db.setUserName("xxx");
db.setPassword("yyyy");
if(!db.open())
{
QMessageBox::information(this,"Message","Not connected...");
}
else{
QSqlQuery query;
query.exec(QString("INSERT INTO `mmr` VALUES (NULL,'%1','%2','%3','%4')")
.arg("musictest").arg("albumtest").arg("timetest").arg("datetest"));
QMessageBox::information(this,"Message","Connected !!!");
}
}
I have the message box "Connected !!!"
This must be a beginner mistake
Instead of construction QString from args try prepared QSqlQuery and binding the values.
http://qt-project.org/doc/qt-5/qsqlquery.html#approaches-to-binding-values
QString doesnt know anything about sql escaping. You use Sqlite driver so instead of connecting to your hostname qt tried sqlite file
From the code you have here it looks like you're not passing the database to QSqlQuery.
Instead of
QSqlQuery query;
try this
QSqlQuery query(db);
I'd also recommend that you take this a step further by creating a separate variable for your sql statement, and then passing that in as an argument along with the database. Like the following:
QString insertSql = QString("INSERT INTO `mmr` VALUES (NULL,'%1','%2','%3','%4')")
.arg("musictest").arg("albumtest").arg("timetest").arg("datetest");
QSqlQuery query(insertSql, db);
This will also allow you to verify that you have a properly constructed sql statement in the debugger before you try to run it.
After this, you can call exec() and store the result in a bool (as others on here have mentioned).
bool checkSuccess = query.exec();
Your code above will run without failing. exec() will just return false since it didn't have anything to run the sql statement against.

Error : In fetching data from DatabaseClosed Connection

I am facing a strange problem while running two test-cases that is present in a TestSuite. The Test suite comprises of 15 Test cases, and these two are 9th and 10 th Tc's respectively.
When i am running only these two test cases both are running fine, but with the whole test suite running these two are not present in the report.(Totally getting skipped)
Both the test cases having a function that executes a databases query and fetches a patient name from database and in console we have seen this is the root cause behind the error.
We are facing "Error :In fetching data from Database Io exception: Connection reset"--9th Tc
In fetching data from DatabaseClosed Connection"--10th Tc
The code we have written is below to fetch the patient name:
try
{
stmt =con.createStatement(); //public static java.sql.Statement stmt;public static ResultSet rs;public static Connection con; these 3 we declared in driver script
rs=stmt.executeQuery("select d.id, c.first_name, c.last_name, d.ssn from Table1 d, Table2 c where c.id=d.contact_id and d.facility_id='"+facilityID+"' and d.security_id='"+securityID+"' and <Some condition> and d.id not in (<Some data>);
if (rs.next() == true){
DBFirstName=rs.getString(2);
DBLastName=rs.getString(3);
DBFullName = DBLastName +", " +DBFirstName;
System.out.println("DB Full Name ="+DBFullName);
}else{
System.out.println("Inside else");
return "Fail :Unable to fetch Patient data(lastname) from database";
}
}
catch(Throwable t)
{
APPLICATION_LOGS.debug("Error : In fetching data from Database" +t.getMessage());
System.out.println("Error : In fetching data from Database" +t.getMessage());
}
rs.close();
stmt.close();
Please let me know if anyone having any idea.
Thanks in advance.
Nilanjan.
Please check if database connection has been open . Con.open() might do the work. And also try checking the stack trace i guess it is coming as soon as you start using the connection as it is not open. Please check and tell

Is there an alternative of using a VBScript for enabling FileStream after SQL Server installation?

To use Filestream on a DB 3 steps must be done:
1) enable it a server/instance level
2) enable it (sp_configure) at DB level
3) create a varbinary(max) field that supports filestream
(2) and (3) are done easily with T-SQL
(1) is doable manually from SQL Server Configuration Manager, basically what I need is to check all the 3 checkboxes:
(source: sql-server-performance.com)
but how is it possible to automize it?
I found this artcile "Enabling filestream usin a VBScript", is there another way to do it than using VBScripts? May be something that is possible to do only with 2008R2?
In case it VBScript is the only solution, which are the possible downsides?
The only way other than clicking in the Configuration Manager is via WMI (which is what the VBScript does). If you don't like VB, here's how I've been configuring it from C# (note that the code needs to run with admin privileges (elevated)):
private ManagementObject GetFilestreamManagementObject(string machineName, string instanceName)
{
string managementPath = string.Format(#"\\{0}\root\Microsoft\SqlServer\ComputerManagement10", machineName);
ManagementScope managementScope = new ManagementScope(managementPath);
managementScope.Connect();
SelectQuery query = new SelectQuery("FilestreamSettings", string.Format("InstanceName='{0}'", instanceName));
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, query))
{
ManagementObjectCollection moc = searcher.Get();
if (1 != moc.Count)
{
string exceptionText = String.Format("Expected single instance of FilestreamSettings WMI object, found {0}.", moc.Count);
throw new FilestreamConfigurationException(exceptionText);
}
ManagementObjectCollection.ManagementObjectEnumerator enumerator = moc.GetEnumerator();
if (false == enumerator.MoveNext())
{
throw new FilestreamConfigurationException("Couldn't move ManagementObjectEnumerator to the first entry.");
}
return (ManagementObject)enumerator.Current;
}
}
private void EnableFilestream(int accessLevel)
{
ManagementObject filestreamSettingsObject = GetFilestreamManagementObject("myMachine", "MSSQLSERVER");
ManagementBaseObject methodArgs = filestreamSettingsObject.GetMethodParameters("EnableFilestream");
methodArgs["AccessLevel"] = accessLevel;
methodArgs["ShareName"] = ""; //default
ManagementBaseObject returnObject = filestreamSettingsObject.InvokeMethod("EnableFilestream", methodArgs, null);
if (returnObject == null)
{
throw new FilestreamConfigurationException("Result of calling filestreamSettingsObject.InvokeMethod(\"EnableFilestream\", methodArgs, null)" is null);
}
uint returnValue = (uint)returnObject.GetPropertyValue("ReturnValue");
const uint errorSuccessRestartRequired = 0x80070BC3;
if (returnValue != 0 && returnValue != errorSuccessRestartRequired)
{
Win32Exception win32Exception = new Win32Exception((int)returnValue);
string exceptionText =
string.Format("'EnableFilestream' method returned {0}: {1}", returnValue, win32Exception.Message);
throw new FilestreamConfigurationException(exceptionText);
}
}
Just run this.
USE master
Go
EXEC sp_configure 'show advanced options'
GO
EXEC sp_configure filestream_access_level, 3
GO
EXEC sp_filestream_configure
#enable_level = 3
, #share_name = N'FS';
GO
RECONFIGURE WITH OVERRIDE
GO
More on this
http://www.mssqltips.com/tip.asp?tip=1489
0 = disabled (this is the default)
1 = enabled only for T-SQL access
2 = enabled for T-SQL access and local
file system access
3 = enabled for T-SQL access, local
file system access, and remote file
system access
You can store the script in a stored procedure and call it from your application or anywhere you want.
Here're links on this topic
http://www.mssqltips.com/tip.asp?tip=1838
Link
http://technet.microsoft.com/en-us/library/cc645923.aspx
http://www.sql-server-performance.com/articles/dba/Configure_Filestream_in_SQL_Server_2008_p1.aspx
EDIT
Answer to your comment.
Here's what I call step 2
CREATE DATABASE Archive
ON
PRIMARY ( NAME = Arch1,
FILENAME = 'c:\data\archdat1.mdf'),
FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,
FILENAME = 'c:\data\filestream1')
LOG ON ( NAME = Archlog1,
FILENAME = 'c:\data\archlog1.ldf')
GO
http://technet.microsoft.com/en-us/library/cc645585.aspx
Check link for all steps
Filestream in Sql Server 2008 Express
Good Luck!
Pawel's solution worked great for us. We were seeing about a 50% failure rate using the VBS -- haven't seen a failure yet with Pawel's approach. Unlike Greg's results, it has worked great for us against a local system. Actually, that's all we have tried it with.
We did have to make a couple of adjustments to Pawel's code. The line
throw new FilestreamConfigurationException("Result of calling filestreamSettingsObject.InvokeMethod(\"EnableFilestream\", methodArgs, null)" is null);
has the final quote character out of place. It should be after the "is null", right before the ");".
We also had to make sure we got the instanceName built correctly. For example, if we had "mymachine\myinstance", we had to make sure that "instanceName=myinstance" and not the full name. Further, if we had "mymachine" (the default instance), we had to have "instanceName=MSSQLSERVER". Maybe that is Greg's problem -- when we had the instanceName set to the wrong thing, we got the same results Greg reports.

PowerBuilder DSN Creation

I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx

Resources