java怎么寫毗連mysql數據庫的模塊,在項目中挪用mysql毗連,查詢表的數據。我的實例是毗連數據庫和封閉毗連,這篇經驗對你進修java有幫忙的話,給我投票或者保藏!http://v.youku.com/v_show/id_XMzkxNzM4MTM1Mg==.html
0數據操作增添刪除更新
0建立數據庫建立表
0毗連數據庫
新建一個java項目:database。
在庫中添加這個文件:mysql-connector-java-5.1.22-bin.jar。
新建一個類:database,加上main這個方式。
打開這個database.java文件,添加代碼(毗連數據庫):
private static Connection conn;
private static Connection getconnection(String mingcheng,String kouling){
if(conn==null){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sheying?useUnicode=true&characterEncoding=utf-8;",mingcheng, kouling);
System.out.println("毗連mysql數據庫當作功!");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("無法毗連mysql數據庫!");
}
return conn;
增添封閉毗連的代碼:
private static void closeconnection(){
if(conn!=null){
conn.close();
conn=null;
System.out.println();
System.out.println("毗連mysql數據庫封閉!");
} catch (SQLException e) {
// TODO 主動生當作的 catch 塊
e.printStackTrace();
在main方式中毗連數據庫和封閉毗連:
Connection conn=database.getconnection("root", "123456");
database.closeconnection();
運行項目,輸出字符串。
在main方式中的代碼點竄為:(輸出表中的數據)
Statement st=conn.createStatement();
ResultSet re=st.executeQuery("select * from shangpinxinxi");
while (re.next()){
System.err.println(re.getString(1)+" "+re.getString(2)+" "+re.getString(3));
re.close();
st.close();
輸出成果如下圖,紅色的字體是表中的數據。
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!