mysql创建statement对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql创建statement对象相关的知识,希望对你有一定的参考价值。

package com.yxq.toolsbean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB
private final String url = "jdbc:mysql://localhost:3306/mysql";
private final String userName = "root";
private final String password = "";
private Connection conn = null;
private Statement stm=null;

/* 通过构造方法加载数据库驱动 */
public DB()
try
Class.forName("com.mysql.jdbc.Driver");
System.out.println("加载数据库成功!");
catch (Exception e)
e.printStackTrace();
System.out.println("加载数据库驱动失败!");


/* 创建数据库连接 */
public void createCon()
try
Connection conn = DriverManager.getConnection(url, userName, password);
System.out.println("获取数据库连接成功!");
catch (Exception e)
e.printStackTrace();
System.out.println("获取数据库连接失败!");


/* 获取Statement对象 */
public void getStm()
createCon();
try
Statement stm=conn.createStatement();
System.out.println("创建Statement对象成功!");
catch (SQLException e)
e.printStackTrace();
System.out.println("创建Statement对象失败!");



我用测试类test测试以上代码
package com.yxq.toolsbean;

public class Test
public static void main(
String[] args)
DB db=new DB();
db.createCon();
db.getStm();



报错为
加载数据库成功!
获取数据库连接成功!
获取数据库连接成功!
Exception in thread "main" java.lang.NullPointerException
at com.yxq.toolsbean.DB.getStm(DB.java:40)
at com.yxq.toolsbean.Test.main(Test.java:10)

有空你们自己把代码粘贴到myeclipse看一下

在JDBC里面,statement只是一个接口并没有实现?那为什么能够创建statement对象?

不要思维定式在 Statement stmt = new Statement();才是创建对象 这种思维上.
创建对象方式有很多 我给你写了个类似的 名字也用了Statement不过只是个名字而已 真实的Statement实现方法你可以看源码,我的代码只是告诉你"创建对象方式有很多"

public interface Statement



public class Preparedment implements Statement
public static Statement getSatementInstance()
return new Preparedment();


现在你可以用以下来创建 一个接口 的对象

Statement stm1 = Preparedment.getSatementInstance();
Statement stm2 = new Preparedment();
参考技术A import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConn

private Connection conn;
String strMysqlURL = "jdbc:mysql://127.0.0.1:3306/bookroom?user=root&password=arone";

public Connection getConnection()

try
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(strMysqlURL);

catch (Exception e)
e.printStackTrace();


return conn;



public static void main(String args[])
DBConn con = new DBConn();

con.getConnection();


public DBConn() // 初始化时建立数据源的连接

this.getConnection();



public synchronized Statement getStmt() throws Exception
Statement stmt;
stmt = conn.createStatement();
return stmt;



// 创建预处理会话对象
public synchronized PreparedStatement getPstmt(String sql) throws Exception
PreparedStatement pstmt=null;
pstmt = conn.prepareStatement(sql);
return pstmt;



// 执行查询操作
public synchronized ResultSet query(String sql) throws Exception
try
Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;

catch (Exception e)
System.out.println(e.toString());
return null;




public boolean hasUserName(String sql) // 判断重复

try
Statement stmt;
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(sql);
rs.next();
if (rs.getString("num").equals("0"))
return false;
else
return true;

catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
return false;




// 执行更新操作
public synchronized int update(String sql) throws Exception
int nn=0;
Statement stmt=null;
try

stmt = conn.createStatement();
nn = stmt.executeUpdate(sql);
catch (Exception e)
System.out.println(e.toString());
nn = 0;

return nn;


// 关闭数据库连接
public void DBclose() throws SQLException
if (conn != null)
try
conn.close();
catch (SQLException e)
e.printStackTrace();


参考技术B 。。靠了,肯定错啊,你那个createCon中的Connection conn是局部变量而且他的值改变又不影响类中的那个Connection对象。你把createCon中别定义Connection conn,直接conn,肯定对
直接用createCon() 返回Connection对象多好,一般都这么写
还有连接两次数据库,没必要,也很危险。追问

把修改后的代码发一下

参考技术C Statement stm=conn.createStatement();
错误的意思是你这里的conn为空

JDBC之Java连接mysql实现增删改查

使用软件:mysql、eclipse

链接步骤:

1.注册驱动 

2.创建一个连接对象

3.写sql语句

4.执行sql语句并返回一个结果或者结果集

5.关闭链接(一般就是connection、statement、setresult)这三个连接对象,关闭顺序一般是(setresult    --->  statement  -->  setresult  )

一、直接连接方法:(这种方法就是讲sql语句和结果所有的步骤写在一起) 不建议使用该方法

 1 public static void main(String[] args) {
 2         String url = "jdbc:mysql://localhost:3306/students";
 3         String user = "root";
 4         String password = "admin";
 5         Connection conn = null;
 6         Statement st = null;
 7         
 8         try {
 9             // 1. 注册驱动
10             Class.forName("com.mysql.jdbc.Driver");
11             // 2. 创建一个链接对象
12             conn = DriverManager.getConnection(url,user,password);
13             // 3. 创建一个sql语句的发送命令对象
14             String sql = "insert into student values(‘2001‘,‘Tom‘,‘20‘,‘7000‘)";        
15             st= conn.createStatement();
16             // 4. 执行sql语句,拿到查询的结果集对象
17             st.executeQuery(sql);20         } catch (Exception e) {
21             e.printStackTrace();
22         }finally {
23             // 5. 关闭链接 ,命令对象 ,结果集
24             if(st != null) {
25                 try {
26                     st.close();
27                 } catch (Exception e) {
28                     e.printStackTrace();
29                 }
30             }
31             if(conn != null) {
32                 try {
33                     conn.close();
34                 } catch (Exception e) {
35                     e.printStackTrace();
36                 }
37             }
38         }

二、建立工具类方法,将必要的几步写一个类,使用的时候直接调用建议使用

1.注册驱动、创建连接对象、关闭资源    这三部一般可以写一个类,由于写sql语句和执行sql语句的结果不一致,所以可以将其在用到的时候在写

2.一般写工具类都是写成静态方法,以方便调用

//这是工具类:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JdbcUtils { private static String driverName = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/student_achievement_system"; private static String user = "root"; private static String password = "admin"; /** * 链接数据库 */ static { try { Class.forName(JdbcUtils.driverName); } catch (Exception e) { e.printStackTrace(); } } /** * 获取链接对象connection * @return */ public static Connection getConnection() { try { return DriverManager.getConnection(JdbcUtils.url, JdbcUtils.user, JdbcUtils.password); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 关闭资源 * @param conn * @param st * @param rs */ public static void close(Connection conn,Statement st,ResultSet rs) { if(rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if(st != null) { try { st.close(); } catch (Exception e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }

  

//这是对数据库的基本操作类

// 增加、删除、更新、查找一条、查找所有的方法

public class StudentsDaoImpl implements IStudentsDao {     //增加 @Override public int save(Students student) { Connection conn = null; PreparedStatement ps = null; try { conn = JdbcUtils.getConnection(); String sql = "insert into students values(?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, student.getStudentId()); ps.setString(2, student.getStudentName()); ps.setString(3, student.getSex()); ps.setString(4, student.getPhoneNo()); ps.setString(5, student.getAddress()); ps.setDate(6, (Date) student.getBirthday()); int row = ps.executeUpdate(); return row; } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.close(conn, ps, null); } return 0; }       //删除 @Override public int delete(int studentId) { Connection conn = null; PreparedStatement ps = null; try { conn = JdbcUtils.getConnection(); String sql = "delete from students where studentId=?"; ps = conn.prepareStatement(sql); ps.setInt(1, studentId); int row = ps.executeUpdate(); return row; } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.close(conn, ps, null); } return 0; }     //更新 @Override public int update(int studentId, Students student) { Connection conn = null; PreparedStatement ps = null; try { conn = JdbcUtils.getConnection(); String sql = "update students set studentName=?,sex=?,phoneNo=?,address=?,birthday=? where studentId=?"; ps = conn.prepareStatement(sql); ps.setString(1, student.getStudentName()); ps.setString(2, student.getSex()); ps.setString(3, student.getPhoneNo()); ps.setString(4, student.getAddress()); ps.setDate(5, ((Date) student.getBirthday())); ps.setInt(6, studentId); int row = ps.executeUpdate(); return row; } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.close(conn, ps, null); } return 0; }       //查找一条数据 @Override public Students getByStudentId(int studentId) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); String sql = "select * from students where studentId=?"; ps = conn.prepareStatement(sql); ps.setInt(1, studentId); rs = ps.executeQuery(); if(rs.next()) { Students student = new Students(); student.setStudentId(rs.getInt("studentId")); student.setStudentName(rs.getString("studentName")); student.setSex(rs.getString("sex")); student.setPhoneNo(rs.getString("phoneNo")); student.setAddress(rs.getString("address")); student.setBirthday(rs.getDate("birthday")); return student; } } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.close(conn, ps, rs); } return null; }       //查找所有数据 @Override public List<Students> getAll() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); String sql = "select * from students"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); List<Students> studentsList = new ArrayList<>(); while(rs.next()) { Students student = new Students(); student.setStudentId(rs.getInt("studentId")); student.setStudentName(rs.getString("studentName")); student.setSex(rs.getString("sex")); student.setPhoneNo(rs.getString("phoneNo")); student.setAddress(rs.getString("address")); student.setBirthday(rs.getDate("birthday")); studentsList.add(student); } return studentsList; } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.close(conn, ps, rs); } return null; }
}

  

 








以上是关于mysql创建statement对象的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis3.4.0以上的分页插件错误:Could not find method on interface org.apache.ibatis.executor.statement.Statem

mysql创建statement对象

java JDBC-statement接口实现简单的sql语句调用

Mybatis插件-查看执行SQL

Mybatis源码剖析-黑马程序员

Java学习笔记8.1.2 初探JDBC - JDBC编程步骤