1.JDBC API:Java DataBase Connectivity(java數(shù)據(jù)庫訪問技術)
a.Connection conn=DriverManager.getConnection(url,"root","passwod")? ? ? ? ?//修通道 建立連接
b.PreparedStatement ps=conn.preparsedStatement(sql)? ? ? ? //貨車 語句
? ? eg,I.sql = "select *from student whrer sname=?";
c.ResultSet rs=ps.executeQuery();? ? ? ? //顯示結果
新建Web項目腾窝、包株依、類擅编。寫入驅(qū)動的三個方法扳剿。
Connection conn=null;
PerpareStatement ps=null;
ResultSet rs=null;
String sql="SELECT * FROM book1";
String url="jdbc:mysql://localhost:3306/demo";
conn=DriverManager.getConnection(url,"user","password");
ps = conn.prepareStatment(sql);
rs = ps.executeQuery();? ? ? ? ?//執(zhí)行查詢
while(rs.next()){
? ? ? ? String sno=rs.getString(1);
? ? ? ? System.out.println(sno);? ? ? ? System.out.println(re.getString(1));
? ? ? ? System.out.println(re.getString(2));
? ??????System.out.println(re.getString(3));
? ??????System.out.println(re.getString(4));
? ??????System.out.println(re.getInt(5));
}
? ? ? ? rs.close();
? ? ? ? ps.close();
? ? ? ? conn.close();
開始時倒入jar包:Class.Class.forName("com.mysql.Drive");
調(diào)整異常:close之前全部包裹進一個異常
close相關的接在其后的finally里弄屡。
下面附上實測代碼:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.jsp.jstl.sql.Result;
public class JDBC {
public static void main(String[] args) {
TODO Auto-generated method stub
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String url = jdbcmysqllocalhost3306bookstor;? 數(shù)據(jù)庫位置? 直接跟數(shù)據(jù)庫名稱
String sql = SELECT? FROM student;? SQL語句
try {? 加載驅(qū)動的異常
Class.forName(com.mysql.jdbc.Driver);
conn = DriverManager.getConnection(url, root, 123456);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();? 獲得數(shù)據(jù)
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getInt(5));
}
} catch (ClassNotFoundException e) {
TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}