JDBC新建資料庫建表並插入資料
阿新 • • 發佈:2021-01-18
技術標籤:Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Study {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/study" ;
Connection conn = DriverManager.getConnection(url, "root", "123456");
Statement stat = conn.createStatement();
stat.executeUpdate("create database hello"); // 建立資料庫hello
url = "jdbc:mysql://localhost:3306/hello";
conn = DriverManager.getConnection(url, "root", "123456");
stat = conn.createStatement();
// 建立表 test
stat.executeUpdate("create table test(id int, name varchar(80))");
//新增資料
stat.executeUpdate("insert into test values(1, '張三')" );
stat.executeUpdate("insert into test values(2, '李四')");
//查詢資料
ResultSet result = stat.executeQuery("select * from test");
while (result.next()) {
System.out.println(result.getInt("id") + " " + result.getString("name"));
}
result.close();
stat.close();
conn.close();
}
}