java想要连接数据库首先要引入数据库驱动包
1 final static String drive = "oracle.jdbc.driver.OracleDriver"; 2 final static String oracleurl = "jdbc:oracle:thin:@xx.xxx.xx.xx:1521:orcl"; 3 final static String DBUSER="studio"; 4 final static String password="studio"; 5 6 public void excuteSearch(String str) 7 { 8 Connection conn = null;//表示数据库连接 9 PreparedStatement stmt= null;//这里用PreparedStatement代替statement是防止Sql注入攻击
10 Class.forName(drive);//使用class类来加载程序 11 conn =DriverManager.getConnection(oracleurl,DBUSER,password); //连接数据库 12 //PreparedStatement接口要通过connection接口来进行实例化操作 13 stmt = conn.prepareStatement(SqlStr); 14 stmt.setString(1, str); 15 ResultSet resultset=stmt.executeQuery(); 17 while(resultset.next()) 18 { 19 cod=new cordinate(resultset.getString("JD"),resultset.getString("WD")); 20 system.out.println("JD:"+cod.getJD()+" WD:"+cod.getWD()); 21 } 22 stmt.close(); 23 conn.close();//关闭数据库 24 }