HTML form connecting to local H2 database - javascript

I am wanting to create an HTML form for entering/viewing data on localhost.
The data is in a file based H2 database on localhost.
Ideally, I'd like to use only client-side javascript and HTML so that the user does not need to run a local web server.
I have found some information here on how to connect: http://blog.jooq.org/2014/06/06/java-8-friday-javascript-goes-sql-with-nashorn-and-jooq/
but am wondering about the next step of how to integrate the connection/SQL queries into the web form.
I am aware that the use of javascript to connect to a database is usually frowned upon for security reasons, but for this use-case, it will only be accessing data on localhost.
Also, are there any recommended javascript libraries that would make this easier?
var someDatabaseFun = function() {
var Properties = Java.type("java.util.Properties");
var Driver = Java.type("org.h2.Driver"); //JDBC interface for H2
var driver = new Driver();
var properties = new Properties();
properties.setProperty("user", ""); // database username
properties.setProperty("password", ""); // database password
try {
var conn = driver.connect(
"jdbc:h2:~/db", properties); // connect to database
// Database code here
}
finally {
try {
if (conn) conn.close();
} catch (e) {}
}
}
someDatabaseFun();

Connecting to a java based database like H2 is not easy with a pure javascript solution (despite the fact that H2 exposes itself via JDBC and HTML).
However, there are certainly ways of working with databases in pure-html. These essentially leverage indexeddb and websql storage mechanisms built into the browser.
an incomplete list of javascript libraries are discussed here http://nolanlawson.com/2015/09/29/indexeddb-websql-localstorage-what-blocks-the-dom/:
Lawnchair
PouchDB
LocalForage
Dexie
Lovefield
LokiJS
AlaSQL
MakeDrive
ForerunnerDB
YDN-DB
These are in addition to working with pure WebSQL. For my purposes, pure WebSQL was the best solution, for example: http://www.tutorialspoint.com/html5/html5_web_sql.htm
I am wiling to lose IE/Firefox compatibility.
But there are also options of shiming WebSQL to IndexedDB, for example:
http://nparashuram.com/IndexedDBShim/
So, in summary, you can work with SQL client side with pure javascript but H2 is not the best DB to do this with. WebSQL has the advantage that the database is actually stored by the browser as an SQLite file (file based storage is important to my application)

I'd like to use only client-side javascript and HTML
Where is your JVM going to run? H2 is a Java database. It runs inside a JVM.
Are you embedding it in a Java Applet?
Are you using Java Web Start?
They would be the only ways I know of to run Java on the client's machine.
Anything else has to connect to a server.
If I were tasked with implementing this, I would run H2 embedded in a Java Applet, then have my javascript talk to the Applet. It's very clunky though, and only keeps data in memory. Why not just keep all your data in javascript arrays?

Related

setting up session variable using only javascript

I am working on setting up a session variable only using JavaScript.
The requirement goes this way, A user logs into my application using SFTP client with UN/key, if I store the UN in a ctx variable its getting cleared after login process. I need the user name value to transfer any file to the back-end using my application. for this I am planning on using a session variable in JavaScript so that the UN will be saved as long as the session is established. I don't see any example with just JavaScript being used. is this possible ? I am not a JavaScript developer.
My application only supports XLS, XML and JavaScript.
I am thinking something like
this is just sudo code.
function username(UNvalue) {
var sessionun;
session.setvalue(sessionun) = UNvalue;
return sessionun;
}
Thanks,
Aswin.

Is it possible to retrive database details using javascript only

I am newbie to javascript. I am just wondering whether is it possible to fetch database details using only javascript. I know javascript is client side component. Normally using method we fetch database details.
public static void main(String args[]) throws SQLException {
//URL of Oracle database server
String url = "jdbc:oracle:thin:#localhost:1632:XE";
//properties for creating connection to Oracle database
Properties props = new Properties();
props.setProperty("user", "scott");
props.setProperty("password", "tiger");
//creating connection to Oracle database using JDBC
Connection conn = DriverManager.getConnection(url,props);
String sql ="select sysdate as current_day from dual";
//creating PreparedStatement object to execute query
PreparedStatement preStatement = conn.prepareStatement(sql);
ResultSet result = preStatement.executeQuery();
while(result.next()){
System.out.println("Current Date from Oracle : " + result.getString("current_day"));
}
System.out.println("done");
}
}
Is it possible to fetch same thing using only javascript which works on any machine like windows,linux and any browsers like mozilla, IE, Safari etc.? Any pointer, suggestion really helpful me to understand power of javascript.
No, it is not possible using client-side javascript.
There are server side javascript options like node.js.
You can take a look at those.
With the websockets feature of HTML5, you can use JavaScript to connect to a certain host and communicate via network. So, it would be technically possible to connect to the database port and send queries and receive results.
https://developer.mozilla.org/en/WebSockets
However, HTML5 is still just a proposal and browsers are only starting to implement its features. Many currently used browsers (like older versions of IE), of course, don't implement any of the features. Besides, there probably aren't any database drivers for JS, so you would have to do all the communication low-level, which you probably don't want to.
The usual way how this is done in web applications is that JavaScript requests the data by AJAX from a server, which then communicates with the database. Those servers are often made in PHP, but you can use your Java code to make a servlet. Basically, all it takes is to move your code to a doGet() or doPost() function of a HttpServlet, pack the classes into a web archive and launch it with Tomcat or Jetty.
JavaScript can only initiate calls to server side code that in turn connects to the database.
A common technique these days is to make AJAX calls (using JavaScript) to call services that will return data from a database.
There are several examples online that describes the technique

javascript and oracle database

Is there anyway so that i can connect to oracle database through javascript and access the database values
It depends on where the JavaScript is running.
In most cases, it runs in a web browser, and that host environment doesn't provide any way to connect to a remote database. Some browsers have built in SQL databases (which were in the HTML 5 specification, I'm not sure if they still are), I think they use SQLite (certainly not Oracle).
If you want to connect to Oracle from a web browser, then you will need some sort of intermediary. This usually means a web server that provides an HTTP based API and uses Perl, PHP, ASP.NET, etc, etc to talk to the database.
Other host environments may provide an Oracle API, but you would have to be more specific about which one you are using.
You could try to create an AJAX application building upon Oracle PL/SQL Gateway. See also http://www.stanford.edu/dept/itss/docs/oracle/10g/appdev.101/b10795/adfns_we.htm .
As it happens, I have long ago written about this: http://www.adp-gmbh.ch/blog/2006/11/30.php .
you can use server-side JScript, although this, i'm pretty sure, is only supported by iis. this is how you accomplish it anyways;
<%#Language="JScript"%>
<%
var sqlbeg = "SELECT * FROM sbc WHERE disp = 'F00' AND rec_uid IS NULL";
var aconn = Server.CreateObject("ADODB.Connection");
var recset = Server.CreateObject("ADODB.Recordset");
aconn.Open("DSN=ACUSQL_SBC;UID=sbc;PWD=sbc;");
recset.Open(sqlbeg, aconn, 3, 3);
%>

Server-side Javascript in production fails to open connection to a named instance of SQL2008

I've got a production site that has been working for years with a SQL Server 2000 default instance on server named MDWDATA. TCP port 1433 and Named Pipes are enabled there. My goal is to get this web app working with a copy of the database upgraded to SQL Server 2008. I've installed SQL2008 with SP1 on a server called DEVMOJITO and tested the new database using various VB6 desktop programs that exercise various stored procs in a client-server fashion and parts of the website itself work fine against the upgraded database residing on this named instance of SQL2008. So, while I am happy that the database upgrade seems fine there is a part of this website that fails with this Named Pipes Provider: Could not open a connection to SQL Server [1231]. I think this error is misleading. I disabled Named Pipes on the SQL2000 instance used by the production site, restarted SQL and all the ASP code still continued to work fine (plus we have a firewall between both database servers and these web virtual directories on a public facing webserver.
URL to my production virtual directory which demos the working page:
URL to my development v-directory which demos the failing page:
All the code is the same on both prod and dev sites except that on dev I'm trying to connect to the upgraded database.
I know there are dozens of things to check which I've been searching for but here are a few things I can offer to help you help me:
The code that is failing is server-side Javascript adapted from Brent Ashley's "Javascript Remote Scripting (JSRS)" code package years ago. It operates in an AJAX-like manner by posting requests back to different ASP pages and then handling a callback. I think the key thing to point out here is how I changed the connection to the database: (I cannot get Javascript to format right here!)
function setDBConnect(datasource)
{
var strConnect; //ADO connection string
//strConnect = "DRIVER=SQL Server;SERVER=MDWDATA;UID=uname;PASSWORD=x; DATABASE=StagingMDS;";
strConnect = "Provider=SQLNCLI10;Server=DEVMOJITO\MSSQLSERVER2008;Uid=uname;Pwd=x;DATABASE=StagingMDS;";
return strConnect;
}
function serializeSql( sql , datasource)
{
var conn = new ActiveXObject("ADODB.Connection");
var ConnectString = setDBConnect(datasource);
conn.Open( ConnectString );
var rs = conn.Execute( sql );
Please note how the connection string differs. I think that could be the problem but I don't know what to do. I am surprised the error returned says "named pipes" was involved because I really wanted to use TCP. The connection string syntax here is the same as used successfully on a different part of the site which uses VBScript which I'll paste here to show:
if DataBaseConnectionsAreNeeded(strScriptName) then
dim strWebDB
Set objConn = Server.CreateObject("ADODB.Connection")
if IsProductionWeb() Then
strWebDB = "DATABASE=MDS;SERVER=MDWDATA;DRIVER=SQL Server;UID=uname;PASSWORD=x;"
end if
if IsDevelopmentWeb() Then
strWebDB = "Provider=SQLNCLI10;Server=DEVMOJITO\MSSQLSERVER2008;Database=StagingMDS;UID=uname;PASSWORD=x;"
end if
objConn.ConnectionString = strWebDB
objConn.ConnectionTimeout = 30
objConn.Open
set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = objConn
This code works in both prod and dev virtual directories and other code in other parts of the web which use ASP.NET work against both databases correctly. Named pipes and TCP are both enabled on each server. I don't understand the string used by the Pipes but I am using the defaults always.
I wonder why the Javascript call above results in use of named pipes instead of TCP. Any ideas would be greatly appreciated.
Summary of what I did to get this working:
Add an extra slash to the connection string since this is server-side Javascript:
Server=tcp:DEVMOJITO\MSSQLSERVER2008,1219;
Explicitly code tcp: as a protocol prefix and port 1219. I learned that by default a named instance of SQL uses dynamic porting. I ended up turning that off and chose, somewhat arbitrarily, the port 1219, which dynamic had chosen before I turned it off. There are probably other ways to get this part working.
Finally, I discovered that SET NOCOUNT ON needed to be added to the stored procedure being called. Otherwise, the symptom is the message: "Operation is not allowed when the object is closed".

How to connect to SQL Server database from JavaScript in the browser?

Can anybody give me some sample source code showing how to connect to a SQL Server 2005 database from JavaScript locally? I am learning web programming on my desktop.
Or do I need to use any other scripting language? Suggest some alternatives if you have them, but I am now trying to do it with JavaScript. My SQL Server is locally installed on my desktop — SQL Server Management Studio 2005 and IE7 browser.
You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)
This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.
A perfect working code..
<script>
var objConnection = new ActiveXObject("adodb.connection");
var strConn = "driver={sql server};server=QITBLRQIPL030;database=adventureworks;uid=sa;password=12345";
objConnection.Open(strConn);
var rs = new ActiveXObject("ADODB.Recordset");
var strQuery = "SELECT * FROM Person.Address";
rs.Open(strQuery, objConnection);
rs.MoveFirst();
while (!rs.EOF) {
document.write(rs.fields(0) + " ");
document.write(rs.fields(1) + " ");
document.write(rs.fields(2) + " ");
document.write(rs.fields(3) + " ");
document.write(rs.fields(4) + "<br/>");
rs.movenext();
}
</script>
Web services
SQL 2005+ supports native WebServices that you could almost use although I wouldn't suggest it, because of security risks you may face. Why did I say almost. Well Javascript is not SOAP native, so it would be a bit more complicated to actually make it. You'd have to send and receive SOAP via XmlHttpRequest. Check google for Javascript SOAP clients.
http://msdn.microsoft.com/en-us/library/ms345123.aspx - SQL native WebServices
http://www.google.com/search?q=javascript+soap - Google results for Javascript SOAP clients
Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.
Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"
Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI
Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount
As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.
Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.
I dont think you can connect to SQL server from client side javascripts. You need to pick up some server side language to build web applications which can interact with your database and use javascript only to make your user interface better to interact with.
you can pick up any server side scripting language based on your language preference :
PHP
ASP.Net
Ruby On Rails
(sorry, this was a more generic answer about SQL backends--I hadn't read the answer about SQL Server 2005's WebServices feature. Although, this feature is still run over HTTP rather than more directly via sockets, so essentially they've built a mini web server into the database server, so this answer is still another route you could take.)
You can also connect directly using sockets (google "javascript sockets") and by directly at this point I mean using a Flash file for this purpose, although HTML5 has Web Sockets as part of the spec which I believe let you do the same thing.
Some people cite security issues, but if you designed your database permissions correctly you should theoretically be able to access the database from any front end, including OSQL, and not have a security breach. The security issue, then, would be if you weren't connecting via SSL.
Finally, though, I'm pretty sure this is all theoretical because I don't believe any JavaScript libraries exist for handling the communications protocols for SSL or SQL Server, so unless you're willing to figure these things out yourself it'd be better to go the route of having a web server and server-side scripting language in between the browser and the database.

Categories

Resources