java连接jdbc

package com.dy.util;

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

public class DBUtil {
	public static void main(String[] args) {
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		System.out.println(conn);
	}
	
	public Connection getConnection() {
		try {
			// add driver
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://10.94.182.44:3306/test", "test", "123456");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch(SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

  测试类

package com.dy.util;

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

import com.mysql.jdbc.Connection;


public class Test {
	public static void main(String[] args) {
		Test test = new Test();
		test.list();
	}
	public void list() {
		DBUtil util = new DBUtil();
		Connection conn = (Connection) util.getConnection();
		String sql = "select name,course,score from student_score";
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()) {
				String name = rs.getString(1);
				String course = rs.getString(2);
				int score = rs.getInt(3);
				System.out.println(name + ":" + course + ":" + score);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

  

posted @ 2017-05-05 19:15  颛顼执锐  阅读(154)  评论(0编辑  收藏  举报