How to connect an sqlite database in javascript ASP - sqlite

Hi I've got this code which uses Access to open/store data in database. I need to convert this to use SQLite. However I'm finding it difficult to find the appropriate connection string. How should I go about doing this? Thanks
var dbaseConnection = Server.CreateObject("ADODB.Connection");
var pathToDbase = Server.MapPath("contacts.mdb");
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + pathToDbase;
dbaseConnection.Open(connectionString);
This is just test code but I am trying to just read and display information from an sqlite database.
<table>
<tr><th>Name</th><th>Surname</th></tr>
<%
var dbaseConnection = Server.CreateObject("ADODB.Connection");
var connectionString = "DRIVER=SQLite3 ODBC Driver; Database= path to test.db; LongNames=0; Timeout=1000; NoTXN=0; SyncPragma=NORMAL; StepAPI=0;";
dbaseConnection.Open(connectionString);
var query = "Select * from test order by name asc";
var recordSet = dbaseConnection.Execute(query);
while (!recordSet.Eof) {
Response.write("<tr><td>" + recordSet("name") + '</td><td>' + recordSet("surname") + "</td></tr>");
recordSet.moveNext();
}
recordSet.Close();
dbaseConnection.Close();
%>
</table>
</body>
I am now getting this error
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
connect failed.
Any thoughts? I've activated 32 bit apps in IIS.

DRIVER=SQLite3 ODBC
Driver;Database=c:\mydb.db;LongNames=0;Timeout=1000;NoTXN=0;
SyncPragma=NORMAL;StepAPI=0;
Reference:
https://www.connectionstrings.com/sqlite/

Related

IBM Informix ODBC driver C# - The cursor has been previously released and is unavailable

Trying to switch database using Database (database name); query and then execute a query on that database in two separate queries.
However, I got this error: The cursor has been previously released and is unavailable. What does this mean?
Here is the code:
using (OdbcCommand command = new OdbcCommand(null, odbcConnection))
{
if (switchDBName != null)
{
command.CommandText = "Database " + switchDBName + ";";
command.ExecuteNonQuery();
Console.WriteLine("Switched to database: " + switchDBName + " Successfully.");
}
command.CommandTimeout = 0;
command.CommandText = query;
using (OdbcDataReader datareader = command.ExecuteReader())
{
DataTable resultDT = new DataTable();
resultDT.Load(datareader);
Console.WriteLine("ExecuteODBCQuery -- Finished. There are " + resultDT.Rows.Count + " rows.");
return resultDT;
}
}
If I'm following the logic correctly:
you have two different database connections;
you create a cursor-based statement using one connection;
you switch to the other database connection;
you get an error indicating that the cursor is not available on the current connection
albeit with not wholly appropriate wording in the error message.
A prepared statement or a cursor-based statement is associated with a connection. The same statement will not work for another connection; you have to recreate the cursor or prepared statement for each database connection.
You must know which connection was used for each prepared statement or cursor-based statement. You can switch connections between uses, but when you try to use a statement, the connection must be the same as was in use when it was prepared.

ASP.NET SqlBulkCopy does not insert all records on server

I don't have any idea why SqlBulkCopy does not insert all of the records from the reader. Code:
using (OleDbDataReader dr1 = cmd.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ss, SqlBulkCopyOptions.TableLock, null))
{
bulkCopy.BulkCopyTimeout = 0;
bulkCopy.BatchSize = 500;
bulkCopy.DestinationTableName = tableName;
try
{
bulkCopy.WriteToServer(dr1);
}
catch (Exception ex)
{
Log.LogSystemLog(ex.ToString());
return false;
}
}
GC.Collect();
dr1.Close();
}
I want to bulkCopy about 300k records. It works when I'm running this from localhost to the same database, but when I run this from the server - it always inserts ~7k records... and no error, or exception. On the server 4GB free RAM are available. On localhost ~ 1,5GB.
I have no idea why it's working properly on localhost, but on the server it is not.
I had the same problem, solved by adding the following to my connection string.
IMEX=1
Example:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath(rutacom) + ";" + "Extended Properties='Excel 12.0 Xml; HDR=YES; IMEX=1'";
In my localhost was working perfectly, but not on server.
Try it :)
Notes:
"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
To always use IMEX=1 is a safer way to retrieve data for mixed data columns. Consider the scenario that one Excel file might work fine cause that file's data causes the driver to guess one data type while another file, containing other data, causes the driver to guess another data type. This can cause your app to crash.

SDL Tridion 2011 SP1 code hangs creating Broker Query object

A client is trying to integrate some Broker Query code in to an existing web application. They have the following code:
public String doItNow(int keyA,
String schemaA,
String templateIdA) throws Exception {
loggerInfo("doItNow.start" +
", key:" + keyA +
", schema:" + schemaA +
", templateId:" + templateIdA);
StringBuffer sb = new StringBuffer();
PublicationCriteria pubCriteria = new PublicationCriteria(keyA);
loggerInfo("doItNow.PC:" + pubCriteria);
SchemaTitleCriteria schemaTitleCriteria = new SchemaTitleCriteria(schemaA);
loggerInfo("doItNow.STC:" + schemaTitleCriteria);
AndCriteria andCriteria = new AndCriteria(pubCriteria, schemaTitleCriteria);
loggerInfo("doItNow.AC:" + andCriteria);
Query query = new Query();
loggerInfo("doItNow.Query.0:" + query);
query.setCriteria(andCriteria);
loggerInfo("doItNow.Query.1:" + query);
String[] results = query.executeQuery();
for (String r : results) {
loggerInfo("doItNow.\tres:" + r);
}
ComponentPresentationAssembler cpa = new ComponentPresentationAssembler(keyA);
loggerInfo("doItNow.CPA:" + cpa);
for (String item : results) {
loggerInfo(":>" + item);
sb.append(cpa.getContent(item, templateIdA));
}
return sb.toString();
}
The code exectues as far as creating the Query object:
Query query = new Query();
At this point it hangs. No errors appear in the cd_core log file to suggest a reason for this. Can anyone suggest areas where can investigate to debug this further, or suggest a solution?
There was known issue with JRE version 1.6.0.29 and MSSQL jdbc driver. You need to either downgrade or upgrade to a different JRE version.
https://forums.oracle.com/forums/thread.jspa?threadID=2301826
The issue seems very similar to the issue reported with the driver and you do not see any error messages either.
Try changing the following line:
query.setCriteria(andCriteria);
to:
query.Criteria = andCriteria;
The SDL LiveContent example has a comment suggesting this change.
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/concept_0AB6D192D7AB4EC18892631F519EF1DD
Have you added the correct includes? (Tridion.ContentDelivery.DynamicContent.Query Namespace)
Also as suggested by Chris, query in tridion 2011 does not have a property as setCriteria.
Use query.Criteria instead.
Also have you implemented the necessary changed in cd_storage_conf.xml?

MySQL Data Access Layer: How do you store your queries?

I've been building this project as the solo dev for a while, and while I'm comfortable in the front end and middle tier, I don't really think I'm doing the database the way I should be, and the reason why is because I simply don't really know of any other way. The way I'm currently getting data is by testing out queries in my MySQL workbench and copying and pasting the SQL as a string literal into a method that makes a call to the DB, pulls the data and hydrates my objects.
This hasn't really been a problem until recently, when I had to create a monster of a query and it got me thinking that maybe there's a better way to do this. I don't have a formal DAL separated out, so I know there's room for improvement there, but I was curious about what the correct way would be to store SQL strings. I assume there is a tool somewhere built into VS10 where I can manipulate and work with SQL as SQL instead of as a string.
You should be doing this in stored procedures. That will basically format and store your query. You set parameters that are passed in from your code, then read out the results.
Example:
The C# method:
private void SetNote()
{
const string sql = "sp_SelectControllerNoteByID";
using (var conn = MocSystem.GetMocDbConnection())
{
using (var comm = new SqlCommand(sql, conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("#ControllerNoteID", ControllerNoteId));
try
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
while (rdr.Read())
{
CommentText = rdr["NoteText"].ToString();
_commentor = new User(new Guid(rdr["NoteAuthor"].ToString()));
CommentDate = (DateTime)rdr["NoteDate"];
MocRequestId = (int)rdr["MocRequestID"];
}
}
}
catch (Exception ex)
{
HasError = true;
ErrorMessage += "\nThere was a problem building the note: " + ex.Message;
}
}
}
}
The stored procedure on the DBMS (sql server in this example):
ALTER proc [dbo].[sp_SelectControllerNoteByID]
#ControllerNoteID int
AS
SELECT
ControllerNoteID,
NoteText,
NoteDate,
NoteAuthor,
MocRequestID
FROM
ControllerNotes
WHERE
ControllerNoteID = #ControllerNoteID
So here we call the stored procedure which in this case is just a simple select statement, then we read it out into an object via ADO. Now, this way, you can modify your query without recompiling. Unless you add parameters, in which case you'll have to update those in your code as well.

Passing databasename to SQL query in webmatrix/razor

I have a form built in webmatrix that will be updating data within a user specified database.
I would like the user to insert their DB name into the form, and have the Database.Open("SQLServerConnectionString"); open based on the users submission.
if not possible, is there a way to simply include the user specified DB name within the SQL query below within webmatrix? Sample of what I have below:
var db = Database.Open("SQLServerConnectionString");
var selectQueryString = "SELECT donor_id,first_name,last_name FROM SUPPORT.dpo.dp WHERE donor_id=#0";
I would like the static "SUPPORT" database in the FROM clause to be updated dynamically based on user input. Any help would be great.
Are you using .mdf files or actual database connection strings? If connection strings you can use the OpenConnectionString method and pass a custom connection string instead of using whats in the web.config.
http://msdn.microsoft.com/en-us/library/gg569301(v=VS.99).aspx
Something like this would probably work:
#{
var databaseName = Request["databaseName"]; //load from request
var connectionString = string.Format("Data Source=.\\SQLExpress;Initial Catalog={0};Integrated Security=True", databaseName);
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}
You can just drop the SUPPORT. prefix as its not necessary for the select statement.

Resources