Test.java
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Connection; import java.sql.Statement; public class Test { static Connection con; // 聲明Connection對象 static Statement sql; // 聲明Statement對象 static ResultSet res; public Connection getConnection() { // 連接數據庫方法 try { Class.forName( "org.gjt.mm.mysql.Driver" ); con = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/test", "root", "0000"); } catch (Exception e) { e.printStackTrace(); } return con; // 返回Connection對象 } // /////////////// public static void insertdata() { Test c = new Test(); con = c.getConnection(); try { sql = con.createStatement(); sql.executeUpdate(" insert into stu values(12,'Shara' ) ;"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Main.java
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Test.insertdata(); System.out.println("finish"); } }
輸出 : finish
記得要加載jar別忘了