第一步:下載jar包
第二步:導入jar包
右鍵項目名,點擊properties;
如圖,點擊add后找到剛剛下載的jar包添加進去,點擊apply and close,添加成功后的項目目錄如圖所示;
?第三步:連接數(shù)據(jù)庫
?建立數(shù)據(jù)庫并在其中建立employee表;
像平常寫程序一樣建立包、類,這里我建了一個數(shù)據(jù)庫連接的包,并在其中建立了一個Example類;
?編寫連接代碼,加載驅動程序;
try
{
Class.forName("com.mysql.cj.jdbc.Driver"); //加載MYSQL JDBC驅動程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("成功加載Mysql驅動程序!");
}
catch (Exception e)
{
System.out.print("加載Mysql驅動程序時出錯!");
e.printStackTrace();
}
?連接數(shù)據(jù)庫,這里的數(shù)據(jù)庫名字是db001,登錄名是root,密碼是自己設置的數(shù)據(jù)庫密碼。
try
{
Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db001","root","自己的數(shù)據(jù)庫密碼");
//連接URL為 jdbc:mysql//服務器地址/數(shù)據(jù)庫名,后面的2個參數(shù)分別是登陸用戶名和密碼
System.out.println("成功連接Mysql服務器!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee where age>25");
while (rs.next())
{
System.out.println(rs.getString("name"));
}
connect.close();
}
catch (Exception e)
{
System.out.print("獲取數(shù)據(jù)錯誤!");
e.printStackTrace();
}
完整代碼:?
package 數(shù)據(jù)庫連接;
import java.sql.*;
public class Example {
public static void main(String args[])
{
try
{
Class.forName("com.mysql.cj.jdbc.Driver"); //加載MYSQL JDBC驅動程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("成功加載Mysql驅動程序!");
}
catch (Exception e)
{
System.out.print("加載Mysql驅動程序時出錯!");
e.printStackTrace();
}
try
{
Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db001","root","你設置的密碼");
//連接URL為 jdbc:mysql//服務器地址/數(shù)據(jù)庫名 ,后面的2個參數(shù)分別是登陸用戶名和密碼
System.out.println("成功連接Mysql服務器!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee where age>25"); //輸出表中年紀大于25的員工
while (rs.next())
{
System.out.println(rs.getString("name"));
}
connect.close();
}
catch (Exception e)
{
System.out.print("獲取數(shù)據(jù)錯誤!");
e.printStackTrace();
}
}
}
運行結果:
文章來源:http://www.zghlxwxcb.cn/news/detail-503929.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-503929.html
到了這里,關于eclipse連接數(shù)據(jù)庫(基礎)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!