import com.mysql.jdbc.Driver;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement;
public class JDBCDemo { ? ? public static void main(String[] args) throws Exception {
? ? ? ? //1 获取连接 ? ? ? ? String url = "jdbc:mysql://IP:Port/db_name"; ? ? ? ? String username = "username "; ? ? ? ? String password = "password "; ? ? ? ? Connection conn = DriverManager.getConnection(url, username, password);
? ? ? ? //2 sql 语句 ? ? ? ? String sql = "select * from account "; ? ? ? ? //3 获取执行sql的对象 ? ? ? ? Statement stmt = conn.createStatement(); ? ? ? ? //4 执行sql ? ? ? ? ResultSet rs = stmt.executeQuery(sql);
? ? ? ? while (rs.next()){ ? ? ? ? ? ? System.out.println("-----------------"); ? ? ? ? ? ? System.out.println("ID:"+rs.getInt("id")+" Name:"+rs.getString("name")+" Age:"+rs.getInt("age")); ? ? ? ? }
? ? ? ? //6 释放资源 ? ? ? ? stmt.close(); ? ? ? ? conn.close(); ? ? } }
|