標籤:style color java os io 資料 for ar
原始碼如下:
import java.sql.*;
public class ConToMySQL {
public static void main(String[] args) {
//這裡"liuyan"是MySql下建立的一個測試資料庫
//3306是MySql資料庫服務的預設連接埠
String url="jdbc:mysql://localhost:3306/liuyan";
String userName = "root";
String password = "yourpassword";
Connection con = null;
try {
//載入磁碟機類
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO: handle exception
System.out.println("載入磁碟機類時出現異常");
}
try {
//擷取資料庫連接
con = DriverManager.getConnection(url,userName,password);
} catch (Exception e) {
// TODO: handle exception
System.out.println("出現SQLException異常");
}
System.out.println("載入磁碟機成功");
//接著就可以操作MySql資料庫了
try {
PreparedStatement preStatement = con.prepareStatement("insert into messages values(?,?,?,?,?)");
preStatement.setString(1, "TestString1");
preStatement.setString(2, "TestString2");
preStatement.setDate(3, new java.sql.Date((new java.util.Date()).getTime()));
preStatement.setString(4, "TestString3");
preStatement.setString(5, "TestString4");
preStatement.executeUpdate();
preStatement.close();
con.close();
System.out.println("寫入MySQL資料庫成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}