简单的应用例子
先导入jar包
代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Firstjdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1)注册加载驱动
Class.forName("com.mysql.jdbc.Driver");
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2)获得连接
String url = "jdbc:mysql://localhost:3307/mydb" ;//mydb为数据库的名称
String user = "root"; //数据库的登录名
String password = "123456"; //数据库的登录密码
Connection conn = DriverManager.getConnection(url, user, password);
//3)创建语句对象
Statement st = conn.createStatement();
//4)执行sql获得结果
String sql = "select * from emp "; //emp为要查询的表名
ResultSet rs= st.executeQuery(sql);
//5)处理结果
while(rs.next()){
System.out.print(rs.getObject(1)+"\t");
System.out.print(rs.getObject(2)+"\t");
System.out.print(rs.getObject(3)+"\t");
System.out.print(rs.getObject(4)+"\t");
System.out.print(rs.getObject(5)+"\t");
System.out.print(rs.getObject(6)+"\t"); //共输出要显示的字段名信息
}
//6)关闭资源
rs.close();
st.close();
conn.close();
}
}