JAVA用实现类操作数据库有点不好懂····我是初学者、求高手讲解讲解
发布网友
发布时间:2022-04-10 15:04
我来回答
共1个回答
热心网友
时间:2022-04-10 16:33
我给你一个oracle的JDBC驱动的简单的例子吧:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class TestOracle { public static Connection dbConn; public static void main(String[] srg) { String driverName = "oracle.jdbc.driver.OracleDriver"; // 加载JDBC驱动 // String dbURL = // "jdbc:sqlserver://192.168.216.222:1500; DatabaseName=HYData"; // //连接服务器和数据库test String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))(CONNECT_DATA =(SERVICE_NAME = fengwei)))"; // 连接服务器和数据库test String userName = "lygtaxi"; // 默认用户名 String userPwd = "lygtaxi"; // 安装sql server 2005时的密码 try { Class.forName(driverName); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection Successful!"); // 如果连接成功 // 控制台输出Connection myQueue();// Successful! } catch (Exception e) { e.printStackTrace(); } } // 查询方法 public static List<Procts> myQueue() { List<Procts> list = new ArrayList<Procts>(); String sql = "select XXX,YYY from AAA"; Statement stm; try { stm = dbConn.createStatement(); ResultSet rs = stm.executeQuery(sql); System.out.println("OKOKOK:"); while (rs.next()) { Procts p = new Procts(); //p.setProctName(rs.getString("LSCHB_SSDW")); //p.setUnitPrice(rs.getString("LSCHB_CPH")); System.out.println("rs.getString(\"XXX\"):"+rs.getString("XXX")); System.out.println("rs.getString(\"YYY\"):"+rs.getString("YYY")); list.add(p); } } catch (SQLException e) { e.printStackTrace(); } finally{ try { //stm.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } }
连接数据库的时候需要驱动,我给的测试代码中已经给出。
同时需要驱动包ojdbc14.jar