您好,登錄后才能下訂單哦!
一、準(zhǔn)備好數(shù)據(jù)庫
例如,MS SQL Server2008環(huán)境下,創(chuàng)建school數(shù)據(jù)庫,內(nèi)含一個(gè)表student(sid,sname,ssex,sage),并添加若干行數(shù)據(jù)。
二、配置數(shù)據(jù)庫驅(qū)動(dòng)文件
1.準(zhǔn)備好(下載)sqlserver2008.jar文件;
2.拷貝下載的jar文件到工程中;
在java工程中創(chuàng)建lib目錄,拷貝數(shù)據(jù)庫驅(qū)動(dòng)jar文件到該目錄
3.添加并在Eclipse的Java工程中配置
(右擊工程,選擇Bulid path–>config Build Path–>addJar,添加jar包)
三、編寫主類,連接數(shù)據(jù)庫,并完成查詢和添加數(shù)據(jù)。
編寫Java類文件,完成
1.連接訪問數(shù)據(jù)庫,
2.查詢數(shù)據(jù)表
3.更新數(shù)據(jù)表(添加,修改)import java.sql.Connection;
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBM { public static void main(String[] args){ //數(shù)據(jù)庫連接參數(shù) String driverStr="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String connStr="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=school";// 可以localhost代替ip地址,端口號(hào)1433 String dbUserName="sa"; String dbPassword=""; Connection conn = null; Statement stmt = null; ResultSet rs = null; //1.連接數(shù)據(jù)庫 try{ Class.forName(driverStr); conn = DriverManager.getConnection(connStr,dbUserName,dbPassword); stmt = conn.createStatement(); System.out.println("數(shù)據(jù)庫建立連接成功!"); }catch(Exception ex){ System.out.println("無法與數(shù)據(jù)庫建立連接!"); System.out.println(ex.toString()); } //2.查詢 try { rs = stmt.executeQuery("select * from student"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //3.顯示 try { while(rs.next()){ System.out.println(rs.getInt("sid")+" "+rs.getString("sname")+" "+rs.getString("ssex")+" "+rs.getInt("sage")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。