---
title: "JDBC例子"
author: "sakyone"
date: "2010-05-18T16:44:39Z"
tags: []
categories: ["编程语言"]
slug: "jdbc"
draft: false
lastmod: "2010-05-18T16:44:56Z"
id: 669116
url: "https://sakyone.iteye.com/blog/669116"
---

JDBC例子

```java
import java.sql.*;

public class MainConnection {
    public static void main(String args[]) {
        final String URL = "jdbc:mysql://×××/×××";
        final String USERNAME = "×××";
        final String PASSWORD = "×××";
        
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        String sql = "select * from picz_version2_album where id = ?";
        
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 1);
            
            ResultSet rs = ps.executeQuery();
            
            while (rs.next()) {
                System.out.println(rs.getString("album_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                    ps = null;
                }
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
    }
}
```