java jdbc如何使用
展开全部
给你看个简单的例子吧:
public class DBUtil {
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConn() {
Connection con = null;
//驱动
String className = "";
//url连接路径
String url = "";
//用户名
String username = "";
//密码
String password = "";
try {
className = DBUtil.getValue("/jdbc.properties", "jdbc.driverClassName");
url = DBUtil.getValue("/jdbc.properties", "jdbc.url");
username = DBUtil.getValue("/jdbc.properties", "jdbc.username");
password = DBUtil.getValue("/jdbc.properties", "jdbc.password");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Class.forName(className);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String u = url+"?user="+username+"&password="+password+"&useUnicode=true&characterEncoding=UTF8";
try {
con = DriverManager.getConnection(u);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭连接资源
*
* @param pst
* @param conn
*/
public static void getClose(PreparedStatement pst, Connection conn) {
try {
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 获取jdbc配置文件内的属性值
* @param fileNamePath 配置文件路径
* @param key 字段名
* @return
* @throws IOException
*/
public static String getValue(String fileNamePath, String key)
throws IOException {
Properties props = new Properties();
InputStream in = null;
try {
// in = new FileInputStream(fileNamePath);
// 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
in = DBUtil.class.getResourceAsStream(fileNamePath);
props.load(in);
String value = props.getProperty(key);
// 有乱码时要进行重新编码
// new String(props.getProperty("name").getBytes("ISO-8859-1"),
// "GBK");
return value;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (null != in)
in.close();
}
}
}
jdbc.properties:
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/XXX
jdbc.username = XXX
jdbc.password = XXX
public class CycleTask extends TimerTask{
PreparedStatement pst = null;
ResultSet rs = null;
Connection conn = null;
@Override
public void run() {
conn = DBUtil.getConn();
StringBuffer sb = new StringBuffer();
sb.append(" INSERT INTO P_SB_TEMP(SB_ID,TEMP_SB,TEMP_HJ,REMARK,DW,ADDTIME) ");
sb.append(" VALUES(?,?,?,?,?,?) ");
try{
pst = conn.prepareStatement(sb.toString());
int index = 1;
pst.setString(index++, "1");
pst.setString(index++, "2");
pst.setString(index++, "3");
pst.setString(index++, "4");
pst.setString(index++, "5");
pst.setTimestamp(index++, new Timestamp(2011, 12, 12, 12, 12, 12, 00));
pst.execute();
}catch (SQLException e1) {
e1.printStackTrace();
}
DBUtil.getClose(pst, conn);
}
}
}
你去试试的
public class DBUtil {
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConn() {
Connection con = null;
//驱动
String className = "";
//url连接路径
String url = "";
//用户名
String username = "";
//密码
String password = "";
try {
className = DBUtil.getValue("/jdbc.properties", "jdbc.driverClassName");
url = DBUtil.getValue("/jdbc.properties", "jdbc.url");
username = DBUtil.getValue("/jdbc.properties", "jdbc.username");
password = DBUtil.getValue("/jdbc.properties", "jdbc.password");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Class.forName(className);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String u = url+"?user="+username+"&password="+password+"&useUnicode=true&characterEncoding=UTF8";
try {
con = DriverManager.getConnection(u);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭连接资源
*
* @param pst
* @param conn
*/
public static void getClose(PreparedStatement pst, Connection conn) {
try {
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 获取jdbc配置文件内的属性值
* @param fileNamePath 配置文件路径
* @param key 字段名
* @return
* @throws IOException
*/
public static String getValue(String fileNamePath, String key)
throws IOException {
Properties props = new Properties();
InputStream in = null;
try {
// in = new FileInputStream(fileNamePath);
// 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
in = DBUtil.class.getResourceAsStream(fileNamePath);
props.load(in);
String value = props.getProperty(key);
// 有乱码时要进行重新编码
// new String(props.getProperty("name").getBytes("ISO-8859-1"),
// "GBK");
return value;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (null != in)
in.close();
}
}
}
jdbc.properties:
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/XXX
jdbc.username = XXX
jdbc.password = XXX
public class CycleTask extends TimerTask{
PreparedStatement pst = null;
ResultSet rs = null;
Connection conn = null;
@Override
public void run() {
conn = DBUtil.getConn();
StringBuffer sb = new StringBuffer();
sb.append(" INSERT INTO P_SB_TEMP(SB_ID,TEMP_SB,TEMP_HJ,REMARK,DW,ADDTIME) ");
sb.append(" VALUES(?,?,?,?,?,?) ");
try{
pst = conn.prepareStatement(sb.toString());
int index = 1;
pst.setString(index++, "1");
pst.setString(index++, "2");
pst.setString(index++, "3");
pst.setString(index++, "4");
pst.setString(index++, "5");
pst.setTimestamp(index++, new Timestamp(2011, 12, 12, 12, 12, 12, 00));
pst.execute();
}catch (SQLException e1) {
e1.printStackTrace();
}
DBUtil.getClose(pst, conn);
}
}
}
你去试试的
展开全部
public class JDBCtest {
//驱动程序就是之前在classpath中配置的jdbc的驱动程序jar中
public static final String drive = "oracle.jdbc.driver.OracleDriver";
/**
* 连接地址,各个厂商提供单独记住
* jdbc:oracle:thin:@localhost:1521:ORCL localhost 是ip地址。
*/
public static final String url = "jdbc:oracle:thin:@192.168.1.15:1521:ORCL";
/**
* 用户 密码
*/
public static final String DBUSER="gyly";
public static final String password="gyly";
public static void main(String[] args){
Connection conn=null;
Statement stmt=null;
ResultSet result=null;
try {
Class.forName(drive);//使用class类来加载程序
conn =DriverManager.getConnection(url,DBUSER,password); //连接数据库
//Statement接口要通过connection接口来进行实例化操作
stmt = conn.createStatement();
//执行SQL语句来查询数据库
result =stmt.executeQuery("SELECT DEPTID,DEPTNAME,ADDR,TEL,FAX,LXR,PX,UNITID FROM bs_dept");
while(result.next()){//判断有没有下一行
int DEPTID =result.getInt(1);
String DEPTNAME = result.getString(2);
String ADDR = result.getString(3);
long TEL = result.getLong(4);
long FAX = result.getLong(5);
String LXR =result.getString(6);
int PX =result.getInt(7);
int UNITID = result.getInt(8);
System.out.print("DEPTID="+DEPTID+";");
System.out.print("DEPTNAME="+DEPTNAME+";");
System.out.print("ADDR="+ADDR+";");
System.out.print("TEL="+TEL+";");
System.out.print("FAX="+FAX+";");
System.out.print("LXR="+LXR+";");
System.out.print("PX="+PX+";");
System.out.print("UNITID="+UNITID+";");
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
result.close();//数据库先开后关
stmt.close();
conn.close();//关闭数据库
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//驱动程序就是之前在classpath中配置的jdbc的驱动程序jar中
public static final String drive = "oracle.jdbc.driver.OracleDriver";
/**
* 连接地址,各个厂商提供单独记住
* jdbc:oracle:thin:@localhost:1521:ORCL localhost 是ip地址。
*/
public static final String url = "jdbc:oracle:thin:@192.168.1.15:1521:ORCL";
/**
* 用户 密码
*/
public static final String DBUSER="gyly";
public static final String password="gyly";
public static void main(String[] args){
Connection conn=null;
Statement stmt=null;
ResultSet result=null;
try {
Class.forName(drive);//使用class类来加载程序
conn =DriverManager.getConnection(url,DBUSER,password); //连接数据库
//Statement接口要通过connection接口来进行实例化操作
stmt = conn.createStatement();
//执行SQL语句来查询数据库
result =stmt.executeQuery("SELECT DEPTID,DEPTNAME,ADDR,TEL,FAX,LXR,PX,UNITID FROM bs_dept");
while(result.next()){//判断有没有下一行
int DEPTID =result.getInt(1);
String DEPTNAME = result.getString(2);
String ADDR = result.getString(3);
long TEL = result.getLong(4);
long FAX = result.getLong(5);
String LXR =result.getString(6);
int PX =result.getInt(7);
int UNITID = result.getInt(8);
System.out.print("DEPTID="+DEPTID+";");
System.out.print("DEPTNAME="+DEPTNAME+";");
System.out.print("ADDR="+ADDR+";");
System.out.print("TEL="+TEL+";");
System.out.print("FAX="+FAX+";");
System.out.print("LXR="+LXR+";");
System.out.print("PX="+PX+";");
System.out.print("UNITID="+UNITID+";");
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
result.close();//数据库先开后关
stmt.close();
conn.close();//关闭数据库
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2018-09-08 · 百度知道合伙人官方认证企业
关注
展开全部
public static void main(String[] args) throws Exception { Connection conn = null; String sql;
String url = "jdbc:mysql://localhost:3306/javademo?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; try { // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来, // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以 Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等 Statement stmt = conn.createStatement(); sql = "create table student(NO char(20),name varchar(20),primary key(NO))"; int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数,如果返回-1就没有成功 if (result != -1) { System.out.println("创建数据表成功"); sql = "insert into student(NO,name) values('2012001','陶伟基')"; result = stmt.executeUpdate(sql); sql = "insert into student(NO,name) values('2012002','周小俊')"; result = stmt.executeUpdate(sql); sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值 System.out.println("学号\t姓名"); while (rs.next()) { System.out .println(rs.getString(1) + "\t" + rs.getString(2));// 入如果返回的是int类型可以用getInt() } } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } } }
String url = "jdbc:mysql://localhost:3306/javademo?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; try { // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来, // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以 Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等 Statement stmt = conn.createStatement(); sql = "create table student(NO char(20),name varchar(20),primary key(NO))"; int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数,如果返回-1就没有成功 if (result != -1) { System.out.println("创建数据表成功"); sql = "insert into student(NO,name) values('2012001','陶伟基')"; result = stmt.executeUpdate(sql); sql = "insert into student(NO,name) values('2012002','周小俊')"; result = stmt.executeUpdate(sql); sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值 System.out.println("学号\t姓名"); while (rs.next()) { System.out .println(rs.getString(1) + "\t" + rs.getString(2));// 入如果返回的是int类型可以用getInt() } } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } } }
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
package com.jingao.mail.util;
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 DBConnection {
public static Connection conn = null;
public static void init() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
try {
conn = DriverManager.getConnection(url, "mail", "mail");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
if (conn == null)
init();
return conn;
}
public static void close(Statement stmt,PreparedStatement pstmt,ResultSet rs){
try {
if (rs!=null)
rs.close();
if (stmt!=null)
stmt.close();
if (pstmt !=null)
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
就是这么用的这是最原始的方法了,加载数据库驱动,静态类得到连接!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
给你个例子
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DataBaseConnection {
private static final String DB_DRIVER = "org.gjt.mm.mysql.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String DB_USER = "root";
private static final String DB_PWD = "mysql";
private Connection conn;
public Connection getConnection() {
try {
if (conn == null || conn.isClosed()) {
Class.forName(DB_DRIVER);
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询