学习java之使用jdbc操作mysql

需要用到mysql for java驱动 mysql-connector-java-5.1.22.tar.gz

下载地址 http://dev.mysql.com/downloads/connector/j/

mysql-connector-java.jar 导入到项目

[codesyntax lang=”java”]

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

public class testdb {

	static Connection conn = null;

	public static void main(String[] args) {
		testdb testdb = new testdb();
		testdb.test();
	}

	public static void getConnectionByJDBC() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("装载驱动包出现异常,请查正!");
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection("jdbc:mysql://192.168.56.101/ye55", "root", "root");
		} catch (SQLException e) {
			System.out.println("链接数据库发生异常!");
			e.printStackTrace();
		}
	}

	public void test() {
		String sql = "select * from user";
		getConnectionByJDBC();
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String username = rs.getString("username");
				String password = rs.getString("password");
				System.out.println(username + " --" + password);
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
				conn.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}
}

[/codesyntax]