日期:2014-05-16  浏览次数:20559 次

MySQL 的JDBC操作一般步骤
package com.laili.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectTest
{
	public static void main(String[] args)
	{
		String connStr = "jdbc:mysql://localhost:3306/testdb";
		Connection conn = null;
		Statement stmt = null;
		
		try
		{
			//数据库访问的一般步骤:
			//1.获得连接
			conn = DriverManager.getConnection(connStr, "root", "7683358");
			
			System.out.println(conn);		
			//2.使用连接创建语句对象
			stmt = conn.createStatement();
			
			//3.使用语句对象执行查询等操作
			ResultSet set = stmt.executeQuery("select * from customers;");
			
			//遍历结果集
			while(set.next())
			{
				int id = set.getInt("id");
				
				String name = set.getString("name");
				
				int age = set.getInt("age");
				
				String address = set.getString("address");
			
				float salary = set.getFloat("salary");
				
				System.out.println(id + " " + name + " " + age + " " + address + " " + salary);		
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(stmt != null)
			{
				try
				{
					System.out.println("query statement closed!");
					stmt.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				}
				stmt = null;
			}
			if(conn != null)
			{
				try
				{
					System.out.println("connction closed!");
					conn.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				}
				conn = null;
			}
		}		
	}
}