JDBC連接MySQL5.7的方法
1.首先準備mysql 和eclipse環(huán)境,在環(huán)境搭建好之后,從eclipse官網(wǎng)下載jdbc的驅(qū)動包,下載地址http://dev.mysql.com/downloads/connector/j/
2.從下載的文件中取出mysql-connector-java-5.1.31-bin.jar,放到工程中,并導入路徑
方法:右擊工程名->Build Path->Configure Build Path,選擇Add External JAR... 找到mysql-connector-java-5.1.31-bin.jar所在的位置,然后將驅(qū)動包加載到項目中,

3.寫個例子測試一下
package testmysql;
import java.sql.*;
public class Test {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/student";
Connection con = null;
try
{
Class.forName(driver);
}
catch(java.lang.ClassNotFoundException e)
{
System.out.println("Connect Successfull.");
System.out.println("Cant't load Driver");
}
try
{
con=DriverManager.getConnection(URL,"root","root");
System.out.println("Connect Successfull.");
}
catch(Exception e)
{
System.out.println("Connect fail:" + e.getMessage());
}
}
}
連接上數(shù)據(jù)庫之后,可以根據(jù)表中的內(nèi)容進行數(shù)據(jù)庫表的查詢,首先表中要有內(nèi)容,將一些信息輸入到表中之后即可使用SQL語言進行查詢
import java.sql.*;
public class Main {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/xiaolu";
Connection con = null;
ResultSet rs = null;
Statement st = null;
String sql = "select * from student";
try
{
Class.forName(driver);
}
catch(java.lang.ClassNotFoundException e)
{
// System.out.println("Connect Successfull.");
System.out.println("Cant't load Driver");
}
try
{
con=DriverManager.getConnection(URL,"root","root");
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs!=null) {
ResultSetMetaData rsmd = rs.getMetaData();
int countcols = rsmd.getColumnCount();
for(int i=1;i<=countcols;i++) {
if(i>1) System.out.print(";");
System.out.print(rsmd.getColumnName(i)+" ");
}
System.out.println("");
while(rs.next()) {
System.out.print(rs.getString("sno")+" ");
System.out.print(rs.getString("sname")+" ");
System.out.print(rs.getString("ssex")+" ");
System.out.print(rs.getString("sage")+" ");
System.out.println(rs.getString("sdept")+" ");
}
}
//System.out.println("Connect Successfull.");
System.out.println("ok");
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("Connect fail:" + e.getMessage());
}
}
}
關(guān)于JDBC連接MySQL5.7的文章就介紹到這,其他的可以查下腳本之家其它相關(guān)文章。
相關(guān)文章
mysql學習之引擎、Explain和權(quán)限的深入講解
這篇文章主要給大家介紹了關(guān)于mysql學習之引擎、Explain和權(quán)限的相關(guān)資料,文中通過示例代碼將引擎、Explain和權(quán)限介紹的非常詳細,對大家學習或者使用mysql具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-06-06
MySQL開發(fā)規(guī)范與使用技巧總結(jié)
今天小編就為大家分享一篇關(guān)于MySQL開發(fā)規(guī)范與使用技巧總結(jié),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
MySQL之DATE_ADD()和DATE_SUB()函數(shù)的使用方式
這篇文章主要介紹了MySQL之DATE_ADD()和DATE_SUB()函數(shù)的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04

