Createstatement java lang nullpointerexception

Java NullPointerException для createStatement

Я разрабатываю приложение для ресторана. Ошибка возникает, когда я пытаюсь инициализировать определенный класс. Вот код.

public class DbItem 

private static Connection conn = null;

static conn = DBConnection.connect();
>
public static ArrayList fetchAll() ArrayList items = new ArrayList<>();
String sql = "select * from itens";
try Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) items.add(new Item(rs.getString("nome"), rs.getString("descricao"), rs.getFloat("preco")));
>
return items;
> catch (SQLException ex) Logger.getLogger(DbItem.class.getName()).log(Level.SEVERE, null, ex);
>
return null;
>
>

public class DBConnection 

private static Connection conn;

public static Connection connect() if(conn == null) String url = "jdbc:mysql://localhost:3306/";
String dbName = "restaurante_comandas_jonnathan";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to " + dbName + " with " + userName);
JOptionPane.showMessageDialog(null, conn == null);
return conn;
> catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) e.printStackTrace();
>
>
return null;
>

>

Я попробовал отладку с помощью всплывающих окон. Я проверил, было ли соединение пустым прямо перед командой return, и выяснилось, что это не так. Затем я проверил после вызова первого скрипта и выяснил, что это действительно так. Теперь, как объект может быть null сразу после извлечения, если он не был до возвращения? Редактировать: Вот. Трассировка стека

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at model.data.DbItem.fetchAll(DbItem.java:48)
at model.Item.getAll(Item.java:76)
at view.PedidoForm.(PedidoForm.java:22)
at view.Login$2.run(Login.java:99)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Источник

How To Resolve java.lang.NullpointerException: Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement()’on a null object reference

Sorry for the post title that so long wkwk you should know what will I write in this post. Yeah, it is about how to resolve :

java.lang.NullpointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()'on a null object reference

This is story about my problem. I have a task to create an API (Application Programming Interface) from Java code, it is like *.jar library that can implemented into some Java project. But this API implemented into Android Application. I think is it possible ways to do it ? And this API using mysql connection to get-post the data from-to database. Normally API for Android Application using from *.php file and output as JSON or XML. But in this case so different wkwkwk cause it is my job so I must try and learn more even though rather difficult and find some error wkwk 😀 and my insane error was called in this post tittle. I’ve been trying many kind solutions but no one fix my problem. From stackoverflow that says :

  • My IP address is wrong, and in different port
  • My jdbc is wrong
  • My jdbc format connection is wrong
  • My service doesn’t run yet

There are no one can fix my problem. And then finally I’ve been read someone post and in his code included this line :

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

He write inside onCreate() method and before connection inititation line. So I try to add that line into my code and run it. Awesome, it is amazing 😀 now my application can run and get data correctly.

How a great this code, just simple sorce code can fix my spinning problem haha give thanks to Allah 🙂 and thank you so much for the reader, hope it will help you. See you again …

Bagikan ini:

Источник

java.lang.NullPointerException at createStatement

send pies

posted 9 years ago

  • Report post to moderator
  • I am dealing with a Java-Web-Application which works with Hibernate and JDBC (I use BoneCP for the Connection-Pooling) to a MS-SQL-Server 2008.
    I use a class to provide the basic-connection (Basicconnection.Java) and a bean to provide some cached values for every session.

    As I deploy it it works fine. Can’t complain. But after a while an exception is thrown and I’m unable to figure out, why:

    Aug 01, 2013 3:00:44 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    java.lang.NullPointerException
    at datenbankbohnen.Persistenzen.initialisiere(Persistenzen.java:100)
    at org.apache.jsp.Partial.Material.Material_jsp._jspService(Material_jsp.java:112)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:722)

    The error occurs in line 22:

    The class Basicconnection looks like this:

    What am I doing wrong? Could it be a connection timeout? As said, during the first ~10 Minutes everything goes as expected. And then just Null pointers and I’m unable to make it work any more.
    Thank you in anticipation!!

    Источник

    NullPointerException при ипользовании createStatement() в MySQL

    Здравствуйте, у меня возникла проблема при написании программы: когда подключаюсь к базе данных MySQL через Connection и использую затема метод createStatement(), выдаёт NullPointerException. Не могу понять в чём дело: база данных есть, таблица есть, драйвер загружен, логин и пароль верные, а всё-равно не работает. Не могли бы вы подсказать, в чём может быть ошибка?
    Код класса, реализующего соединение с базой:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    package reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DatabaseWorker { private Connection con = null; public DatabaseWorker() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/requests", "root", ""); } catch (ClassNotFoundException ex) {} catch (SQLException e) {} } public void SendRequest(Request request) throws SQLException { Statement message=con.createStatement(); //на этой строке выдаёт NullPointerException } }

    Источник

    Читайте также:  Php if file is not empty
    Оцените статью