连接数据库的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class main{
public static void main(String[]args){
Connnection con;//声明Connection对象
String driver="com.mysql.jdbc.Driver";//驱动程序名
String url="jdbc:mysql://localhost:3306/sqltestdb";//url指向要访问的数据库名的mydata
String user="root";
String password="123456";
//遍历查询结果集
try{
Class.forName(driver);
//getConnection方法连接数据库
con=DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the database");
//创建Statement对象来执行sql语句
Statement statement=con.createStatement();
String sql="select * from emp";// 要执行的sql语句
ResultSet rs=statement.excuteQuery(sql); //ResultSet类用来存放结果集
System.out.println("--------------");
System.out.println("执行结果如下:");
System.out.println("---------------");
System.out.println("姓名"+"\t"+"职称");
System.out.println("--------------");
String job=null;
String id=null;
while(rs.next()){
//获取stuname这列数据
job=rs.getString("job");
id=rs.getString("ename");
System.out.println(job+"\t"+id);
}
rs.close();
con.close();
}catch(ClassNotFoundException e){
System.out.println("sorry,i can‘t find driver");
e.printStackTrace();
}catch(SQLException e){
e.printStacktrace();
}catch(Exception e){
e.printStackTrace();
}
finally{
System.out.println("数据库成功获取到数据");
}
}
}