java连接数据库并执行sql

来源:互联网 发布:mac克隆是什么意思 编辑:程序博客网 时间:2024/05/21 10:27
  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();
}
}
}
0 0
原创粉丝点击