Cant make connection with MariaDB and Java - 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..

Related

How Interface can refer to object where no interface is implemented?

I created a connection to a mysql database. Below is my code
package org;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DatabaseConn {
public static void main(String[] args) {
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
try {
String host = "jdbc:mysql://localhost:3306/sys";
String username = "root";
String password = "root";
Connection Con = DriverManager.getConnection(host, username, password);
Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );
System.out.println("Records:"+rs);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
My Understanding towards Interface implementation on classes says, Interface type reference to an object of class that implements Interface.
But when I investigated below code snippet used in above code..
Connection Con = DriverManager.getConnection(host, username, password);
DriverManager.getConnection(host, username, password) returns a reference(of type Connection) to a object but no interface is implemented in class DriverManager. Can anyone clear my this doubt ..? Or I missed out anything ?
Same thing am not able to get with below code snippet
Statement SQL = Con.createStatement();
Con.createStatement() should return a reference to a object that implements Statement interface. But this Connection interface is implemented by ConnectionImpl class where implementation is present like below
public class ConnectionImpl
extends ConnectionPropertiesImpl
implements Connection {
public Statement createStatement()
throws SQLException
{
return createStatement(1003, 1007);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
{
checkClosed();
StatementImpl stmt = new StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
}
Let's look at this bit by bit:
DriverManager.getConnection(host, username, password) returns a reference (of type Connection) to a object...
This is correct.
...but no interface is implemented in class DriverManager.
This is also correct.
What your explanation is missing is that DriverManager.getConnection() doesn't return a reference to the DriverManager. It returns a reference to an object of a different class, one that does implement the Connection interface.
Let's say for the sake of argument that there is a class called MySqlConnection:
class MySqlConnection implements Connection {
...
}
Now, DriverManager.getConnection() could well return an instance of this class:
class DriverManager {
public Connection getConnection(...) {
return new MySqlConnection(...);
}
}
Hope this clears things up.
getConnection and createStatement are factory methods. Note that the interface is implemented in the returning object class.
Only the interfaces like DriverManager, Connection , Statement etc. are declared in the JDK , the concrete classes which implement them are there in the corresponding JDBC driver you use. For ex., in your case it is mysql jdbc driver added in your class path. So, it is these concrete implementations in the driver jar that knows how to connect to the Database and talk to it. JDK has just defined the specification in the form of interfaces that all the vendor classes should implement. This makes the java code independent of any change in the Database and the corresponding driver.

How do I import .jar and use its class and also how do i use stmt from a .jar file in netbeans?

It's 1:37am here so I'm greeting you all a good day.
I've got a problem here and I'm really really new to java. Please have patience on me. :(
I've got a .jar file that I imported to my Libraries in my netbeans project. It's called dbconnect.jar. I want to create a statement in my Fruits.java that will change my stmt statement (from inside dbconnect.jar) to whatever mysql statement i want it to be (specifically, I want to add fruits to my db). Here's my project map:
So inside my dbconnect.jar contains the class Dbconnect. Here are the contents of Dbconnect:
package dbconnect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dbconnect {
public Connection conn = null;
public Statement stmt = null;
public ResultSet rs = null;
public Dbconnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String Host = "jdbc:mysql://localhost/dbname";
String Username = "root" ;
String Password = "";
conn = DriverManager.getConnection(Host, Username, Password);
stmt = conn.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
}
By the way, I'm using xampp for Apache and Mysql.
So my questions are, how do I call/import this dbconnect.jar of mine so I can use it in Fruits.java (and if possible, am I able to use extends here?) and how do I make it so that I can edit the stmt part in dbconnect.jar using Fruits.java ?
This is currently what's inside the add button from my UI in Fruits.java:
I really need help with this. Thank you so much in advance!
Oh and I'm still a starter. So I hope there will be no advanced codes. Thanks again!
And yes, I'm using JFrame. Here's what it looks like for now.
Since, you have Dbconnect.jar on your classpath you can just say something like this in your Fruit.java class:
Dbconnect db = new Dbconnect();
This will create a new object of Dbconnect class with name db.
In order for you to be able to edit the statement you'll have to create a new method and not just call it in the constructor.
Here is an example:
public void connect(String myStatement) {
/* Do Something */
}
You can then call connect() function on db object you created before.

How to achieve separation of concerns without using any framework but Tomcat + Servlets?

I have a code that works fine. The important parts are as follows:
My model class:
package biz.tugay.sakila.model;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:48 */
public class Actor {
private long id;
private String firstName;
private String lastName;
// Getters, setters...
}
My dao class:
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:12 */
import biz.tugay.sakila.model.Actor;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ActorDao {
protected static final Connection connection = DBConnector.getConnection();
public List<Actor> getAllActors() throws SQLException {
List<Actor> allActors = new ArrayList<Actor>();
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM Actor";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
// You get the idea... Setters again..
allActors.add(actor);
}
rs.close();
stmt.close();
return allActors;
}
}
and the DBConnector
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:35 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sakila";
static final String USER = "root";
static final String PASS = "";
private static Connection connection = null;
public static final Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
return connection;
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
throw new UnsupportedOperationException();
}
}
}
My Servlet class:
package biz.tugay.sakila.servlet;
/* User: koray#tugay.biz Date: 26/06/15 Time: 14:31 */
import biz.tugay.sakila.dao.ActorDao;
import biz.tugay.sakila.model.Actor;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
#WebServlet(urlPatterns = "/actors")
public class ActorServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ActorDao actorDao = new ActorDao();
List<Actor> allActors = null;
try {
allActors = actorDao.getAllActors();
req.setAttribute("allActors",allActors);
req.getRequestDispatcher("/actors.jsp").forward(req, resp);
} catch (SQLException e) {
}
}
}
And /actors.jsp will show an HTML table to the user.
I have made this exercise myself with the sakila sample database MySQL provides.
My question is, without using any framework such as Spring or Struts, how can I achieve a better separation? For example, currently ActorServlet depends on ActorDao concretely, can I fix this, if so how? Also ActorDao depends heavily on DBConnector. For example, I want to be able to create a NoSQL connector and use it, but currently I can not I guess?
First step is to abstract out some interfaces. For example, make ActorDao an interface, move the implementation to ActorDaoImpl or whatever. Create an ActorDaoFactory that hands you an ActorDao which is, under the covers, an ActorDaoImpl, but the servlet doesn't need to know that.
Second step is more complex... if you want to only use Tomcat, then injection and the like is out, but you can configure Tomcat to create these new interfaces and put them in JNDI. This process is probably too complex to put in an answer here, but the Tomcat documentation on JNDI is really nice. The process basically involves creating a factory, like I advocated above, and then having Tomcat invoke that factory through configuration.
Once you do this, looking them up from JNDI is as simple as
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our DAO
ActorDao ad = (ActorDao)envCtx.lookup("dao/actor");
Good luck!

HTTP Callback in Java

I'm trying to write some code to handle the process of an HTTP callback in Java.
I have very little knowledge of Java and was hopping you could lend me a hand or point me in the right way.
I want to call the script from a page that will listen for a POST from other machine with some parameters and their values.
I then want the script to save them somewhere (a file or a database).
Any help would be really appreciated.
For further clarification, I want to create a servlet on a specific URL to handle a HTML post from another machine and receive all parameters and their values and insert them into a database for example.
Another edit, got to this code so far:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class CallbackServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
String instId=req.getParameterValues("instId")[0];
String cartId=req.getParameterValues("cartId")[0];
String desc=req.getParameterValues("desc")[0];
String cost=req.getParameterValues("cost")[0];
String amount=req.getParameterValues("amount")[0];
String currency=req.getParameterValues("currency")[0];
String name=req.getParameterValues("name")[0];
String transId=req.getParameterValues("transId")[0];
String transStatus=req.getParameterValues("transStatus")[0];
String transTime=req.getParameterValues("transTime")[0];
String cardType=req.getParameterValues("cardType")[0];
Connection conn = null;
Statement stmt = null;
PrintWriter out=res.getWriter();
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");
stmt = conn.createStatement();
int i=stmt.executeUpdate("insert into orderdetails values('"+transId+"','"+instId+"','"+cartId+"','"+desc+"'"+cost+"','"+amount+"','"+currency+"','"+name+"','"+transStatus+"','"+transTime+"','"+cardType+")");
if(i>0)
out.println("Inserted Successfully");
else
out.println("Insert Unsuccessful");
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
}
I can't test it atm unfortunately. Could you guys take a look at it and point out any mistakes/improvements?
Cheers
Probably easiest way for this would be to use Servlet api with some Java application server (tomcat, jetty, ...).Look at http://www3.ntu.edu.sg/home/ehchua/programming/java/javaservlets.html

Thread main Suspended

my code is given below and i hav created a user class also
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
// print the results
System.out.println(user);
usersList.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
new UserServicesDAO().get_all_data();
}
}
i got the output, only last_update gives me null value. I have changed it to timestamp but no effect...in the debug gives me error:
Thread main suspended
UserServicesDAO.get_all_data() line24
UserServicesDAO.main(String[]) line56
what's the problem plz give me a solution..
I see only two reasons for user.last_update to be null:
It's null in the database. Check your data. Check that everything is committed. Check that you're querying the correct database.
setLast_update() doesn't actually set the field last_update field. Show us the code of User to confirm or infirm.
Also, please respect the Java naming conventions.
I think the problem is with your database. Make sure resultSet is returning the right type.
For example:
resultSet.getInt("id");
might be
resultSet.getLong("id");
this can cause you troubles. At least this happened to me once. You should check for other fields name,email,mobile.
Also be careful about date
resultSet.getString("last_update")
if in your database "last_update" column type is not string, this can also cause you problems

Categories

Resources