Java數據庫編程(MySQL爲例):
package com.lovo.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import com.lovo.bean.GroupBean;
public class TestInsert {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GroupBean gp = new GroupBean("", "", 4);
/*
* 告知驅動管理器,配置MySQL數據庫應用
* 即---加載驅動
*/
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* 獲取連接
*/
Connection con = null;
try {
//通過驅動管理器獲取連接---三個參數:URL, 用戶名、密碼
//URL---統一資源定位符---格式如: http://192.168.5.12:9527/index.html
// 協議 :// 對方機器的IP地址:端口號/資源名
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testquery?useUnicode=true&characterEncoding=utf8", "root", "lovo");
/*
* 書寫sql語句
*/
String sql = "insert into t_group (f_groupName,f_groupAddress,f_groupNum) " +
"values('"+gp.getGroupName()+"','"+gp.getGroupAddress()+"',"+gp.getGroupNum()+")";
/*
* 利用連接創建獲取語句對象--Statement
*/
Statement stat = con.createStatement();
/*
* 語句對象執行SQL
*/
int row = stat.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
/*
* 關閉連接
*/
if(con != null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}