public class SqlConnection{ //SQLServer //private static String url="jdbc:sqlserver://localhost:1433;databaseName=test"; //private static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //MYSQL private static String driver="com.mysql.jdbc.Driver"; private static String url="jdbc:mysql://127.0.0.1:3306/test"; private static String username="root"; private static String password="root"; private static Connection conn; static{ try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getconn(){ try { conn=DriverManager.getConnection(url,username,password); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void closeconn(){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
使用方法:
PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery("SELECT * FROM ...") ; int rows = pstmt.executeUpdate("INSERT INTO ...") ;