1. 程式人生 > >java連線MySQL--JDBC

java連線MySQL--JDBC

1.建立工程匯入mysql-connect-bin.jar (Build Path)
2.載入驅動
Class.forName(“com.mysql.jdbc.Driver”); //載入驅動
3.建立連線
DriverManager.getConnection(url,user,password);
4.執行語句
5.處理結果

程式碼:
package com.my;
import java.sql.*;
public class SqlFuntion {
public static Connection getConnect() throws SQLException {
try
{
Class.forName("com.mysql.jdbc.Driver"); //載入驅動
return DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","123456");
//建立連線
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
public static int update(String sql) throws SQLException
{
Connection conn = getConnect();
PreparedStatement ps = conn.prepareStatement(sql);
//將sql語句提交到資料庫進行預編譯
int x=ps.executeUpdate();
if(ps!=null)
ps.close();
if(ps!=null)
conn.close();
return x;
}
public static void query(String sql) throws SQLException
{
Connection conn = getConnect();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("name")+"\t"+rs.getString("grade")+"\t"+rs.getString("age")+"\t");
}
if(ps!=null)
ps.close();
if(ps!=null)
conn.close();
}
}