`

java连接数据库

 
阅读更多
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 DatabaseConnection {

	public static void main(String[] args) {
		statement();
		preparedStatement();
	}
	//创建Statement连接数据库
	public static void statement(){
		try {
			Class.forName("driverclass");
			Connection conn = DriverManager.getConnection("url", "user", "password");
			Statement stmt = conn.createStatement();
			ResultSet rs =  stmt.executeQuery("sql");
			while(rs.next()){
				System.out.println(rs.getString(0));
			}
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
	}
	//创建PreparedStatement连接数据库
	public static void preparedStatement(){
		try {
			Class.forName("driverclass");
			Connection conn = DriverManager.getConnection("url", "user", "password");
			PreparedStatement pstmt = conn.prepareStatement("select * from test where id=?");
			//参数设值 索引从1开始的 !!!
			pstmt.setString(1, "id");
			ResultSet rs =  pstmt.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString(0));
			}
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics