大叔经验分享(94)jdbc连接mysql、sqlserver、oracle
Mysql
driver下载:https://mvnrepository.com/artifact/mysql/mysql-connector-java
import java.sql.*; public class SqlServerTest { public static void main(String []args) { String driverName="com.mysql.jdbc.Driver"; String dbURL="jdbc:mysql://$ip:3306/$db"; String userName="$user"; String userPwd="$password"; try { Class.forName(driverName); Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd); Statement st = dbConn.createStatement(); ResultSet rs = st.executeQuery("select * from user"); while (rs.next()) { System.out.println(rs.getString(1)); } System.out.println("success!"); } catch(Exception e) { e.printStackTrace(); System.out.print("fail!"); } } }
SqlServer
driver下载:https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4/4.0
import java.sql.*; public class SqlServerTest { public static void main(String []args) { String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String dbURL="jdbc:sqlserver://$ip:1433;DatabaseName=$db"; String userName="$user"; String userPwd="$password"; try { Class.forName(driverName); Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd); Statement st = dbConn.createStatement(); ResultSet rs = st.executeQuery("select * from sysobjects where xtype='U'"); while (rs.next()) { System.out.println(rs.getString(1)); } System.out.println("success!"); } catch(Exception e) { e.printStackTrace(); System.out.print("fail!"); } } }
Oracle
driver下载:https://www.oracle.com/database/technologies/jdbc-drivers-12c-downloads.html
import java.sql.*; public class SqlServerTest { public static void main(String []args) { String driverName="oracle.jdbc.driver.OracleDriver"; String dbURL="jdbc:oracle:thin:@//$ip:1521/$db"; String userName="$user"; String userPwd="$password"; try { Class.forName(driverName); Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd); Statement st = dbConn.createStatement(); ResultSet rs = st.executeQuery("select * from all_tab_comments"); while (rs.next()) { System.out.println(rs.getString(1)); } System.out.println("success!"); } catch(Exception e) { e.printStackTrace(); System.out.print("fail!"); } } }
---------------------------------------------------------------- 结束啦,我是大魔王先生的分割线 :) ----------------------------------------------------------------
- 由于大魔王先生能力有限,文中可能存在错误,欢迎指正、补充!
- 感谢您的阅读,如果文章对您有用,那么请为大魔王先生轻轻点个赞,ありがとう