Save a fingerprint template into a database mysql - java - java

I am developing a project with the sdk fingerprint of Griaule , and as a start I'm creating a program without a GUI that allows the user to scan his fingerprint and store it in a mysql database already created earlier.
I'm here to ask you a hand with regard to storing the fingerprint in the database.
In the program I created, I captured the fingerprint, I extracted the template from the fingerprint through a function I call extract () .
After that I should call another function , enroll (), which allows me to save the fingerprint in a database.
Even looking at the SDK examples I did not understand how it works, can someone help me? thanks in advance! :)
public void enroll() {
try {
//Inserts the template on the database
enrollStmt.setBinaryStream(1,new ByteArrayInputStream(template.getData()), template.getData().length);
enrollStmt.executeUpdate();
//Picks the ID generated for it.
ResultSet rs = insertedIdStmt.executeQuery();
rs.next();
ui.writeLog("Fingerprint enrolled with id = "+Integer.toString(rs.getInt(1)));
} catch (SQLException e) {
ui.writeLog("Error enrolling template");
}
}

It is saving the finger print data as BLOB in the database. Blob (Binary Large Object) is nothing but a byte array representation of information, mainly used to store images etc in database. In your case, the fingerprint information is being stored.
enrollStmt.setBinaryStream(1,new ByteArrayInputStream(template.getData()), template.getData().length);
In this line, the bytearrayinputstream is created using the data in the template object. template.getData is giving you the byte[] representation of the fingerprint information. Then the byte[] is getting saved in database, by
enrollStmt.executeUpdate();
Whereas, the following query gives you the id for the data stored, for your use.
ResultSet rs = insertedIdStmt.executeQuery();

Ok thank you very much Hirak , so I open a new connection with a function I created called initdb () , structured as follows:
private void initDB() {
try {
//Loads the JDBC driver.
Class.forName("com.mysql.jdbc.Driver").newInstance();
/**Connection to the Database.*/
Connection db;
String user = "root";
String password = "";
// connect to a memory database
db = DriverManager.getConnection("jdbc:mysql://localhost:3306/impronte?user=" + user + "&password=" + password);
Statement stm = (Statement) db.createStatement();
//Creates the statements that will be executed on the database,
enrollStmt = db.prepareStatement("INSERT INTO persona(template) values(?)");
insertedIdStmt = db.prepareStatement("SELECT MAX(ID) FROM persona");
} catch (Exception e) {
System.out.println("Error connecting to the database.");
System.out.println(e.getMessage());
}
}
and inside the enroll function this code, but nevertheless gives me the error("Error enrolling template"):
public void enroll ( Template template ) throws GrFingerJavaException {
try {
//Inserts the template on the database
enrollStmt.setBinaryStream(1,new ByteArrayInputStream(template.getData()), template.getData().length);
enrollStmt.executeUpdate();
//Picks the ID generated for it.
ResultSet rs = insertedIdStmt.executeQuery();
rs.next();
System.out.println("Fingerprint enrolled with id = "+Integer.toString(rs.getInt(1)));
System.out.println("Fingerprint enrolled");
} catch (SQLException e) {
System.out.println("Error enrolling template");
}
}

You need to set the template to the template class of the sdk you are using before calling the binaryStream, see what I meant: Line 6 if I'm correct.
public void enroll ( Template template ) throws GrFingerJavaException {
try {
//Inserts the template on the database
Template temp = template;
if(temp != null){
byte[] b = temp.serialize();
enrollStmt.setBytes(1, b);
}
enrollStmt.executeUpdate();
//Picks the ID generated for it.
ResultSet rs = insertedIdStmt.executeQuery();
rs.next();
System.out.println("Fingerprint enrolled with id = "+Integer.toString(rs.getInt(1)));
System.out.println("Fingerprint enrolled");
} catch (SQLException e) {
System.out.println("Error enrolling template");
}
}

Related

Can’t print tables from a database with JDBC

I'm trying to figure out how to get this piece of code, initially made for MySQL, to work with (Microsoft) SQL Server.
When it's called, it's supposed to print out the flight destinations stored as tables in the database, (dbo.) London, (dbo.) NewYork etc. But right now, it won't print anything, no errors either.. I’m using the default MSSQL schema name, dbo.
public void viewFlights(Connection conn) throws SQLException {
String SCHEMA_NAME="${dbo}";
try {
DatabaseMetaData metaData = conn.getMetaData();
String[] tableType = {"TABLE"};
ResultSet rs = metaData.getTables(null, SCHEMA_NAME, null, tableType);
while (rs.next()) {
String tableName = rs.getString(3);
System.out.println(tableName);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Any idea what I've missed here?
Either set a default scheme for you database or
Use Schema name as
String SCHEMA_NAME="{schema.dbo}";
Solved by David Browne's comment!

How can you get a JTextField to work in a SQLite Select statement?

I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output

Willena sqlite jdbc cannot open SqlCipher db

I am trying to figure out how to encrypt a sqlite database in non-android java.
It does not seem to be super straight forward, but I Willena jdbc crypt which does seem to be able to create an encrypted database, but I simply cannot figure out how to access a SQLCipher 4 encrypted database with it.
Here is my code.
String path = "jdbc:sqlite:C:\\Users\\User1\\Desktop\\testServer232.db";
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(path+"?cipher=sqlcipher&key=a");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(3, 'leo1')");
statement.executeUpdate("insert into person values(4, 'yui1')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e.getMessage());
}
}
This code does work, but I don't think that it produces a SqlCipher 4 encrypted database. When I try to open it with DB browser for Sqlite, it does not allow me access when I put the password = a.
Where am I going wrong?
Ok, so I ended up finding the creator of the repository. And he solved it easily and answered really fast.
Here is the solution:
Here are a few things that could be tested:
Use version 3.31.1
Try to do the database connection using "jdbc:sqlite:file:C:\Users\User1\Desktop\test.db?cipher=sqlcipher&key=password123"as URI (notice the added "file:").
Try to add the legacy parameter for SQLCipher as available here (https://github.com/Willena/sqlite-jdbc-crypt#aes-256-bit-cbc---sha1sha256sha512-hmac-sqlcipher). The URI will become something like this: "cipher=sqlcipher&key=password123&legacy=4"
This is now working for me. I recommend that others use it if they are interested in an easy way to do sqlcipher version 4 similarly to how it is done in an android project.

Why I didn't get results when adding Where clause to my query?

I'm using Mysql JDBC driver.. but I have some problem..
the problem is when I use SELECT Query in java source code.
When I use this query:
select * from [name of table]
I've gotten result of query from DB successfully.
but when I use this query:
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
I've not gotten result of query from DB..
The difference thing is just that using where or not.
What's the problem?
How can I solve this problem?
this is my code below
this query isn't working
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
this query is working very well
select * from student;
The difference thing is just only query information .. rest of the source code is the same absolutely
I added my java source code
public class Center {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sql = "select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ";
String url = "jdbc:mysql://localhost:3306/test";
String driverName = "com.mysql.jdbc.Driver";
String id = "root";
String password = "jsyun0415";
Connection con = null;
PreparedStatement prepareState = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list_second = new ArrayList<String>();
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println("Failed to load JDBC driver..");
e.printStackTrace();
return;
}
try {
con = DriverManager.getConnection(url, id, password);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
list.add(rs.getNString("stu_no"));
list_second.add(rs.getNString("stu_ename"));
}
//test = list.get(2);
} catch (SQLException sqex) {
System.out.println("SQLException: " + sqex.getMessage());
System.out.println("SQLState: " + sqex.getSQLState());
} finally {
try {
if (stmt != null)
stmt.close();
if (con != null)
con.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You will need to set the the character encoding in the JDBC connection URL:
String url = "jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8";
Otherwise the character encoding between client and server is automatically detected upon connection, this means that the Korean text in your query will be wrongly encoded and will probably cause the query to return zero results.
You can read more about this in the MySQL JDBC driver documentation - Using Character Sets and Unicode
This answer suggests that there's no problem with the Java code; it's your data.
Can you run the query in the MySQL admin tool and get back a result set that's not empty? If yes, there's a problem with your Java code. There must be an error that you either aren't supplying or you swallow with an empty catch block.
Do you get an error message or stack trace, or is the result set empty? If it's the latter, perhaps there is no student row with number 20001001.
MySQL function "substring" parameter 0 is wrong, only more then zero allowed.

Java, code works, but exception is still thrown

I am creating a simple registration frame that adds records onto a database. It gives me an error message every time it runs the SQL query that adds records in the database, however it still adds them, but because of that my programs gets to a standstill, instead of opening another window.
here's that part of the code:
regButton.addActionListener(new ActionListener() {
#Override public void actionPerformed( ActionEvent e ) {
//Execute when button is pressed
if( uNameField.getText().equals("")
|| new String(newPassField.getPassword()).equals("")
|| new String(repeatPassField.getPassword()).equals("") ) {
errorLabel.setForeground(Color.red);
errorLabel.setText("Some fields are left blank");
}
else if( new String(newPassField.getPassword()).equals(
new String(repeatPassField.getPassword()))){
Statement stmt;
ResultSet res;
try
{
//SET USERNAME AND PASSWORD FROM FIELDS TO UPPER CASE
String username = uNameField.getText().toUpperCase();
String password = new String(newPassField.getPassword()).toUpperCase();
//SQL INSERT QUERY
String sql;
sql = "INSERT INTO Employees VALUES ('" +username +"','" +password +"');";
stmt = con.createStatement();
res = stmt.executeQuery(sql);
System.out.println("Added to database!");
con.close();
}
catch(SQLException exe) {
System.out.println("Error creating or running statement: " + e.toString());
try {
con.close();
}
catch(Exception eex){}
}
}
else {
errorLabel.setForeground(Color.red);
errorLabel.setText("Password missmatch");
}
}
Every time it registers a new employee (user) it displays this "Error creating or running statement: ..... " although, I can find the newly added employees in the employee list.
What may be causing this problem?
Before we get to your specific problem, some general advice:
Connection con = ...
try {
// your stuff
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The way you are doing it now not only swallows the exception, but also avoids printing its stacktrace. And close must be performend once and only once, regardless of the exception.
If you are on Java 7, this would be much easier:
try (Connetion con = ...) {
// stuff to do
}
catch (Exception e) {
e.printStackTrace();
}
The closing in a finally is now done automatically.
Specifically about your exception, you execute an INSERT by calling executeQuery. This method sends the statement to the DB, which properly executes it, but its response back to the JDBC is not a ResultSet. This is where it blows up, after the record is already inserted. Since you are in autocommit mode, there is no transaction to roll back. Lesson: always use transactions.
You need to use executeUpdate for SQL INSERTs
int rowCount = stmt.executeUpdate(sql);
I hate seeing code written this way. You didn't ask about this, and my comment won't solve your problem, but I think it needs to be said.
You're creating a maintenance nightmare for yourself by putting persistence code in a Swing Listener method.
A better idea is to think about objects in a way that gives them a single responsibility.
Take your persistence code and move it into a separate class that you can develop and test on its own. Once it's working, give a reference to the class that needs it.
Your code will be more modular, easier to test, more reusable, and less of a nightmare to understand.
Uncle Bob Martin has a succinct mneumonic for this and other ideas worth remembering: SOLID.
why dont you try PreparedStatement
try{
//SET USERNAME AND PASSWORD FROM FIELDS TO UPPER CASE
String username = uNameField.getText().toUpperCase();
String password = new String(newPassField.getPassword()).toUpperCase();
//SQL INSERT QUERY
PreparedStatement pstmt = con.prepareStatement("insert into Employees values(?,?)");
pstmt.setString(1,username);
pstmt.setString(2,password);
if(!pstmt.execute())
{
//means your code worked correctly
System.out.println("Inserted successfully");
}
else
{
System.out.println("Unsuccessfull");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}

Categories

Resources