get data from postgres into a .jsp page - java

i guess this is a newbie question...Don't seem to find it anywhere, so i thought i asked, hope you don't get mad :) I am really new to all this jsp and java thing and try to figure out what's going on.
So, I have created 2 classes that create the connection to my postgres database. The thought was to have a class that creates the connection and use it anytime i need it, cause i will need to retrieve data many times in the future.
The first one: DbContract.java
package Database;
public class DbContract
{
public static final String HOST = "jdbc:postgresql://localhost:5432/";
public static final String DB_NAME = "DB_1";
public static final String USERNAME = "postgres";
public static final String PASSWORD = "12345";
}
and the second one: TestConnection.java
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestConnection
{
public static void main(String[] args)
{
try
{
Class.forName("org.postgresql.Driver");
Connection c;
c = DriverManager.getConnection(
DbContract.HOST+DbContract.DB_NAME,
DbContract.USERNAME,
DbContract.PASSWORD);
System.out.println("DB connected");
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
}
Now, i want to use these, in order to retrieve data from a existing database i have (postgres and it is filled with records.), BUT from a jsp page. Is it possible?
Can anyone, help me step by step to do it, or is it too easy?
thanks in advance

Related

Cant make connection with MariaDB and Java

Im trying to create web app using java and mariadb but i encountered problem when tried to implement mariadb to login. Here my code:
initSql:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
#WebServlet("/initSql")
public class initSql extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public initSql() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
Connection conn = null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/baza_new", "root","root");
System.out.println("db povezana");
}catch(Exception e){
//JOptionPane.showMessageDialog(null, e);
System.out.println("db NIiiJE povezana");
//return null;
}
}
}
LoginDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.initSql;
public class LoginDAO {
static Connection con = null;
public static boolean validate(String username, String password, String type) {
boolean status = false;
try {
con = initSql.init();
System.out.println("1");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
//pst.setString(1, type);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
status= rs.next();
con.close();
}catch(Exception e) {System.out.print(e);}
return status;
}
}
and i get markers:
Cannot make static reference to non-static method from type generic servler
Type mistmatch cannot connect from void to Connection
I'm little bit stuck with this problem.Can someone help me with my code?
People seem to be neglecting the more broad-scale issues in your code. There are standards to follow like capitalization etc but overall you have some bigger issues.
You shouldn't be making erroneous instances of initSql as it's an HttpServlet, it just doesn't make sense. You also have static/non-static references to a Connection field when you don't need it. To start with, change initSql#init to return a Connection, and while I normally wouldn't recommend abusing static this way, make the method itself static:
//returns a connection, requires no class instance
public static Connection init(ServletConfig config) { ... }
From there, we can now retrieve a Connection instance by calling this method:
Connection con = initSql.init();
Overall you should have a proper class or design for handling this, but for simple learning this is "okay".
Secondly, you're not quite using ResultSet correctly. #next will determine if there is an available row to point to from the SQL results, and if so it moves the marker to the next row. You would use it in order to check if you can retrieve results:
ResultSet set = /* some sql query */;
String someField;
if (set.next()) {
//gets the value of the column "my_field"
someField = set.getString("my_field");
} else {
//no results!
someField = null;
}
Alternatively, if you were looking for multiple results you can loop over #next
while (set.next()) {
//just one value out of many
String myField = set.getString("my_field");
}
In this use-case it's alright to check if the row exists, but I would personally check against something like user permissions or somesuch. If you relied on code like this for something sensitive you might expose something you don't want to.
Overall, I would work a little more on your logical structure for the code, and maybe go over some of the basics for Java and common coding standards for it (Google and Oracle have good guides for this).
Firstly, your class name initSql should have Capitalized first letter to follow conventions.
Secondly, you should either create an instance/object of InitSql and then call the method init() on that object or make the init() method static.
initSql.init() isn't static, which is not a problem of MariaDB and its connection from Java :) To fix this error you can add static to the mentioned method. But: As there are multiple errors in your code (e.g. assigning the result of a void method to a variable), it will not work then either..

SQLite driver is not suitable

I'm trying to connect to database with SQLite. There is no error appears in editor, but when I run the application I am getting error message that says;
"java.sql.SQLException: No suitable driver found for jdbc:sqlite//school.sqlite"
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String SQCONN = "jdbc:sqlite//school.sqlite";
public static Connection getConnection() throws SQLException {
try {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection(SQCONN);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return null;
}
}
I did download the latest sqlite driver to library which is "sqlite-jdbc-3.23.1"
Can anybody help me for this error message? Thankyou,
If anybody sees this post and having the same problem, I just changed
private static final String SQCONN = "jdbc:sqlite//school.sqlite";
to fullpath;
private static final String SQCONN = "jdbc:sqlite:/C:/Users/MAMI/Desktop/OKUL/SchoolSystem/src/school.sqlite";
as #a_horse_with_no_name mentioned. Works fine now.
Thanks again

Trying to use a different variable that I have already declared in a different .java file in my new file

This is probably a simple fix or issue, but I am new to java and not sure how to do it. I have a web service that I am creating and a bunch of java files that I have with different data inputs. I want to be able to use the variables already defined in my other java files in my new file. Below you will see my code. For example on the first part of code, SponsorOrganizationalIdentifier is a column name in my MySQL database, along with a name already declared in other java files. How do I use the different variables that I have already declared in my other webserivce .java files?
Thanks for all your help!
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
String sql = "INSERT INTO tableName values(':SponsorOrganiationalIdentifier', ':AgencyPersonGUID',':PersonID')";
String mySponsorID ="";
mySponsorID = "local"
sql = sql.replace(":SponsorOrganizationIdentifier", );
System.out.println(sql);
String AgencyGUID =""
AgencyGUID =
sql = sql.replace(:AgencyPersonGUID, )
System.out.println(sql)
String PersonIdent
PersonIdent =
sql = sql.replace(:PersonID,)
System.out.println(sql)
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
If you have constant data like column names, consider creating a class then defining them as static final class data.
For example:
class TestClass {
public static final String MY_COLUMN_NAME = "COLUMN_NAME";
}
Then you can access this variable in another class using TestClass.MY_COLUMN_NAME .
If the data is not final (constant) then this becomes a more complicated problem which is solved by writing a correctly structured program.

How to use data from a Webservice on Eclipse to populate a database in MySQL

I want to be able to use my web service to be able to populate a database in MySQL. From the code below, I have connected to the database that I want to populate. How can I use the data that users import on my Web Service to populate MySQL database exchangeInformation. The Web service is working and everything works. I am just looking to be able to use the input of that data from the web service to populate my database in MySQL.
Any help would be greatly appreciated.
Thanks
Code Below:
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
Use this page to see an example of creating a statement from a connection object and executing a query with it. As to your webservice information, I do not see where you are passing it in. That said you can use some simple string replacement to handle that:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
sql = sql.replace(":value1", dataFromService);
Something along those lines should get you started.
EDIT FOR CLARITY:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
String dataFromService = "EDIT";
sql = sql.replace(":value1", dataFromService);
System.out.println(sql);
Would net you an output:
INSERT INTO tableName values('EDIT',':value2','value3', etc)

How to Authenticate Minecraft Login/Any other website login

So I know that this may have come up a few times, but this is actually a little different. I want to authenticate a login from the authentication server. This is my code:
import java.sql.*;
public class TestConnect {
public static void main(String args[]) {
String host = "https://authserver.mojang.com";
String user = "--username--";
String pass = "--password--";
try {
Connection con = DriverManager.getConnection(host, user, pass);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
So the error im getting everytime is the following:
No driver found for https://authserver.mojang.com
A little help would be welcome :)
Read the getConnection method's doc:
http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String,%20java.util.Properties)
url - a database url of the form jdbc:subprotocol:subname
Your url is not valid.

Categories

Resources