您的位置:首页 > 编程语言 > Java开发

java连接数据库并执行sql

2014-08-02 10:20 239 查看
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50

import java.sql.*;public class JDBCTest2 {public static void main(String[] args){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/open";
String user = "root";
String password = "";try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);if(!conn.isClosed())System.out.println("Succeeded connecting to the Database!");
Statement statement = conn.createStatement();
String sql = "select SNO,SNAME from student order by SNO desc limit 0,5";
ResultSet rs = statement.executeQuery(sql);System.out.println("-----------------");System.out.println("执行结果如下所示:");System.out.println("-----------------");System.out.println(" 编号" + "\t" + " 名字");System.out.println("-----------------");String name = null;while(rs.next()) {
name = rs.getString("SNAME");
//name = new String(name.getBytes("ISO-8859-1"),"GB2312");
System.out.println(rs.getString("SNO") + "\t" + name);}rs.close();conn.close();} catch(ClassNotFoundException e) {System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace();} catch(SQLException e) { e.printStackTrace();} catch(Exception e) { e.printStackTrace();}}}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: