Jdbc连接数据库方法

Jdbc连接数据库是经常用到的方法,本文总结下,以备后用:

 

首先,把数据库连接信息写入配置文件:database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

 

接着写获取连接的实现

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcConn {
	
	public static Connection getConnection(){
		 //连接MySql数据库,用户名和密码都是root   
		 Connection conn = null;
		 Properties properties = getprop(); 
	     String driverString = properties.getProperty("driver");  
	     String dburl = properties.getProperty("url");  
	     String username = properties.getProperty("username");  
	     String password = properties.getProperty("password");
	     try{   
	    	 Class.forName("com.mysql.jdbc.Driver");
	    	 Class.forName(driverString);
	    	 conn =   DriverManager.getConnection(dburl , username , password ) ;   
	     }catch(SQLException se){   
	    	 System.out.println("数据库连接失败!");   
	    	 se.printStackTrace() ;   
	     } catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	     return conn;
	}

	private static Properties getprop() {  
        Properties properties = new Properties();  
        try {  
        	InputStream inputStream = Object.class.getResourceAsStream("/database.properties");  
            properties.load(inputStream);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return properties;  
    }  
}

 

最后测试连接是否成功

	public static void main(String[] args) {
		String sql = "select * from user limit 2";
		Connection conn = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		try{
			conn = JdbcConn.getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString(2));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
	}

 

本文参考文章:http://zheng0324jian.iteye.com/blog/1176932

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值