java使用JDBC连接Mysql 代码 并作连接测试程序
代码如下:
package yt; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MySqlTest { /** * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub Connection con = null; //数据库连接 Statement stmt = null; //执行SQL语句 ResultSet rs = null; //结果集 String sql = "select * from ecs_admin_user where user_id = 1"; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载MySql驱动成功!"); con = DriverManager.getConnection("jdbc:mysql://localhost/ecshop?user=root&password=&useUnicode=true&characterEncoding=UTF8"); stmt = con.createStatement(); rs = stmt.executeQuery(sql); String t = null; while(rs.next()){ t = rs.getString("user_name"); } if(t!=null){ System.out.println("用户名为:"+t); }else{ System.out.println("没有找到用户!"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ rs.close(); stmt.close(); con.close(); } } } |