本文目錄一覽:
- 1、java連接mysql數據庫
- 2、java是怎麼連接mysql數據庫的
- 3、java連接數據庫mysql代碼及簡單訪問數據庫
- 4、java怎麼連接mysql數據庫
- 5、eclipsejee怎麼連接mysql數據庫
java連接mysql數據庫
步驟如下,
1. 在開發環境中加載指定數據庫的驅動程序。
接下來的實驗中,使用數據庫MySQL,所以需要下載MySQL支持JDBC的驅動程序(mysql-connector-java-5.1.18-bin.jar)。
2. 開發環境是MyEclipse,將下載得到的驅動程序加載進開發環境中。
3. 在Java程序中加載驅動程序。
在Java程序中,通過 “Class.forName(“指定數據庫的驅動程序”)”
方式來加載添加到開發環境中的驅動程序,例如Class.forName(“com.mysql.jdbc.Driver”)。
4. 創建數據連接對象:通過DriverManager類創建數據庫連接對象Connection。
DriverManager類作用於Java程序和JDBC驅動程序之間,用於檢查所加載的驅動程序是否可以建立連接,然後通過它的getConnection方法,根據數據庫的URL、用戶名和密碼,創建一個JDBC
Connection 對象。代碼如:Connection connection = DriverManager.getConnection(“連接數據庫的URL”, “用戶名”,
“密碼”)。
其中,URL=協議名+IP地址(域名)+端口+數據庫名稱;用戶名和密碼是指登錄數據庫時所使用的用戶名和密碼。具體示例創建MySQL的數據庫連接代碼如下:
Connection connectMySQL =
DriverManager.geiConnection(“jdbc:mysql://localhost:3306/myuser”,”root”
,”root” );
5. 創建Statement對象:Statement 類的主要是用於執行靜態 SQL
語句並返回它所生成結果的對象。
通過Connection 對象的 createStatement()方法可以創建一個Statement對象。例如:Statement statament =
connection.createStatement(); 具體示例創建Statement對象代碼如下:Statement statamentMySQL =connectMySQL.createStatement();
6. 調用Statement對象的相關方法執行相對應的 SQL
語句:通過execuUpdate()方法用來數據的更新,包括插入和刪除等操作,例如向staff表中插入一條數據的代碼:
statement.excuteUpdate( “INSERT INTO
staff(name, age, sex,address, depart, worklen,wage)” + ” VALUES (‘Tom1’, 321,
‘M’, ‘china’,’Personnel’,’3′,’3000′ ) “) ;
7. 通過調用Statement對象的executeQuery()方法進行數據的查詢,而查詢結果會得到
ResulSet對象,ResulSet表示執行查詢數據庫後返回的數據的集合,ResulSet對象具有可以指向當前數據行的指針。通過該對象的next()方法,使得指針指向下一行,然後將數據以列號或者字段名取出。如果當next()方法返回null,則表示下一行中沒有數據存在。使用示例代碼如下:
ResultSet resultSel =
statement.executeQuery( “select * from staff” );
8. 關閉數據庫連接:使用完數據庫或者不需要訪問數據庫時,通過Connection的close() 方法及時關閉數據連接。
java是怎麼連接mysql數據庫的
使用java連接MySQL數據庫與其他的數據庫連接核心是一樣的,如果說區別,那就是所需的驅動不一樣。
工具/原料
MySQL、JDK
方法/步驟
1、首先需要安裝好JDK(配置環境變量),如圖所示:
2、其次要安裝好MySQL數據庫,可以使用可視化Navicar For MySQL,如圖所示:
3、最後通過代碼進行連接。
(1)確定連接路徑URL:
String url=”jdbc:mysql://localhost(可以是本機IP地址):3306(端口號)/mysqltest(數據庫名稱)?”+”user=用戶賬號password=用戶密碼useUnicode=字符編碼”;
(2)加載驅動:
Class.forName(“com.mysql.jdbc.Driver”);
(3)連接,獲取Connection對象
Connection conn=DriverManager.getConnection(url)
(4)可以通過conn對象檢驗連接與否。
java連接數據庫mysql代碼及簡單訪問數據庫
import java.sql.*;
public class DataBasePractice {
public static void main(String[] args) {
//聲明Connection對象
Connection con;
//驅動程序名
String driver = “com.mysql.jdbc.Driver”;
//URL指向要訪問的數據庫名mydata
String url = “jdbc:mysql://localhost:3306/mydata”;
//MySQL配置時的用戶名
String user = “root”;
//MySQL配置時的密碼
String password = “root”;
//遍歷查詢結果集
try {
//加載驅動程序
Class.forName(driver);
//1.getConnection()方法,連接MySQL數據庫!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println(“Succeeded connecting to the Database!”);
//2.創建statement類對象,用來執行SQL語句!!
Statement statement = con.createStatement();
//要執行的SQL語句
String sql = “select * from student”;
//3.ResultSet類,用來存放獲取的結果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println(“—————–“);
System.out.println(“執行結果如下所示:”);
System.out.println(“—————–“);
System.out.println(” 學號” + “\t” + ” 姓名”);
System.out.println(“—————–“);
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數據
name = rs.getString(“stuname”);
//獲取stuid這列數據
id = rs.getString(“stuid”);
//首先使用ISO-8859-1字符集將name解碼為字節序列並將結果存儲新的字節數組中。
//然後使用GB2312字符集解碼指定的字節數組。
name = new String(name.getBytes(“ISO-8859-1″),”gb2312”);
//輸出結果
System.out.println(id + “\t” + name);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//數據庫驅動類異常處理
System.out.println(“Sorry,can`t find the Driver!”);
e.printStackTrace();
} catch(SQLException e) {
//數據庫連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println(“數據庫數據成功獲取!!”);
}
}
}
在上面while代碼段後面添加以下代碼段:
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數據
name = rs.getString(“stuname”);
//獲取stuid這列數據
id = rs.getString(“stuid”);
//首先使用ISO-8859-1字符集將name解碼為字節序列並將結果存儲新的字節數組中。
//然後使用GB2312字符集解碼指定的字節數組。
name = new String(name.getBytes(“ISO-8859-1″),”gb2312”);
//輸出結果
System.out.println(id + “\t” + name);
}
PreparedStatement psql;
ResultSet res;
//預處理添加數據,其中有兩個參數–“?”
psql = con.prepareStatement(“insert into student values(?,?)”);
psql.setInt(1, 8); //設置參數1,創建id為5的數據
psql.setString(2, “xiaogang”); //設置參數2,name 為小明
psql.executeUpdate(); //執行更新
//預處理更新(修改)數據
psql = con.prepareStatement(“update student set stuname = ? where stuid = ?”);
psql.setString(1,”xiaowang”); //設置參數1,將name改為王五
psql.setInt(2,10); //設置參數2,將id為2的數據做修改
psql.executeUpdate();
//預處理刪除數據
psql = con.prepareStatement(“delete from student where stuid = ?”);
psql.setInt(1, 5);
psql.executeUpdate();
//查詢修改數據後student表中的數據
psql = con.prepareStatement(“select*from student”);
res = psql.executeQuery(); //執行預處理sql語句
System.out.println(“執行增加、修改、刪除後的數據”);
while(res.next()){
name = res.getString(“stuname”);
id = res.getString(“stuid”);
name = new String(name.getBytes(“ISO-8859-1″),”gb2312”);
System.out.println(id + “\t” + name);
}
res.close();
psql.close();
java怎麼連接mysql數據庫
這裡介紹兩種方式:
一,jdbc鏈接MySQL數據庫:
1,如果你用jdbc方式,則按照下列方式進行連接:
A,註冊驅動
B,鏈接數據庫
C,執行sql
D,返回結果集
如下為一個基本完整流程:
package com.hu.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBHelper {
public static final String url = “jdbc:mysql://127.0.0.1/student”;
public static final String name = “com.mysql.jdbc.Driver”;
public static final String user = “root”;
public static final String password = “root”;
public Connection conn = null;
public PreparedStatement pst = null;
public DBHelper(String sql) {
try {
Class.forName(name);//指定連接類型
conn = DriverManager.getConnection(url, user, password);//獲取連接
pst = conn.prepareStatement(sql);//準備執行語句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2,將註冊,鏈接封裝好,執行sql語句,返回結果集,代碼如下:
package com.hu.demo;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Demo {
static String sql = null;
static DBHelper db1 = null;
static ResultSet ret = null;
public static void main(String[] args) {
sql = “select *from stuinfo”;//SQL語句
db1 = new DBHelper(sql);//創建DBHelper對象
try {
ret = db1.pst.executeQuery();//執行語句,得到結果集
while (ret.next()) {
String uid = ret.getString(1);
String ufname = ret.getString(2);
String ulname = ret.getString(3);
String udate = ret.getString(4);
System.out.println(uid + “\t” + ufname + “\t” + ulname + “\t” + udate );
}//顯示數據
ret.close();
db1.close();//關閉連接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3,查詢結果如下:
二,利用框架鏈接MySQL,這裡是springMVC+Mybatis方式鏈接,主要是配置文件:
config.properties文件
validationQuery=SELECT 1
#jdbc_url=jdbc\:mysql\://110.80.10.198\:3306/irrigation?useUnicode\=truecharacterEncoding\=UTF-8zeroDateTimeBehavior\=convertToNull
#jdbc_username=root
#jdbc_password=2025900
jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=truecharacterEncoding=UTF-8zeroDateTimeBehaviorsss=convertToNull
jdbc_username=root
jdbc_password=123456
spring-mabatis.xml文件,進行相關配置
?xml version=”1.0″ encoding=”UTF-8″?
beans xmlns=””
xmlns:xsi=”” xmlns:tx=””
xmlns:aop=””
xsi:schemaLocation=”
“
!– 配置數據源 —
bean name=”dataSource” class=”com.alibaba.druid.pool.DruidDataSource”
init-method=”init” destroy-method=”close”
property name=”url” value=”${jdbc_url}” /
property name=”username” value=”${jdbc_username}” /
property name=”password” value=”${jdbc_password}” /
!– 初始化連接大小 —
property name=”initialSize” value=”0″ /
!– 連接池最大使用連接數量 —
property name=”maxActive” value=”20″ /
!– 連接池最小空閑 —
property name=”minIdle” value=”0″ /
!– 獲取連接最大等待時間 —
property name=”maxWait” value=”60000″ /
!– property name=”poolPreparedStatements” value=”true” / property
name=”maxPoolPreparedStatementPerConnectionSize” value=”33″ / —
property name=”validationQuery” value=”${validationQuery}” /
property name=”testOnBorrow” value=”false” /
property name=”testOnReturn” value=”false” /
property name=”testWhileIdle” value=”true” /
!– 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 —
property name=”timeBetweenEvictionRunsMillis” value=”60000″ /
!– 配置一個連接在池中最小生存的時間,單位是毫秒 —
property name=”minEvictableIdleTimeMillis” value=”25200000″ /
!– 打開removeAbandoned功能 —
property name=”removeAbandoned” value=”true” /
!– 1800秒,也就是30分鐘 —
property name=”removeAbandonedTimeout” value=”1800″ /
!– 關閉abanded連接時輸出錯誤日誌 —
property name=”logAbandoned” value=”true” /
!– 監控數據庫 —
!– property name=”filters” value=”stat” / —
property name=”filters” value=”mergeStat” /
/bean
!– myBatis文件 —
bean id=”sqlSessionFactory” class=”org.mybatis.spring.SqlSessionFactoryBean”
property name=”dataSource” ref=”dataSource” /
!– 自動掃描entity目錄, 省掉Configuration.xml里的手工配置 —
property name=”mapperLocations” value=”classpath:com/fourfaith/*/mapping/*.xml” /
/bean
bean class=”org.mybatis.spring.mapper.MapperScannerConfigurer”
property name=”basePackage” value=”com.fourfaith.**.dao” /
property name=”sqlSessionFactoryBeanName” value=”sqlSessionFactory” /
/bean
!– 配置事務管理器 —
bean id=”transactionManager”
class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”
property name=”dataSource” ref=”dataSource” /
/bean
!– 攔截器方式配置事物 —
tx:advice id=”transactionAdvice” transaction-manager=”transactionManager”
tx:attributes
tx:method name=”add*” propagation=”REQUIRED” /
tx:method name=”append*” propagation=”REQUIRED” /
tx:method name=”insert*” propagation=”REQUIRED” /
tx:method name=”save*” propagation=”REQUIRED” /
tx:method name=”update*” propagation=”REQUIRED” /
tx:method name=”modify*” propagation=”REQUIRED” /
tx:method name=”edit*” propagation=”REQUIRED” /
tx:method name=”delete*” propagation=”REQUIRED” /
tx:method name=”remove*” propagation=”REQUIRED” /
tx:method name=”repair” propagation=”REQUIRED” /
tx:method name=”delAndRepair” propagation=”REQUIRED” /
tx:method name=”import*” propagation=”REQUIRED” read-only=”false”
rollback-for=”java.lang.Exception” /
tx:method name=”get*” propagation=”SUPPORTS” /
tx:method name=”find*” propagation=”SUPPORTS” /
tx:method name=”load*” propagation=”SUPPORTS” /
tx:method name=”search*” propagation=”SUPPORTS” /
tx:method name=”datagrid*” propagation=”SUPPORTS” /
tx:method name=”*” propagation=”SUPPORTS” /
/tx:attributes
/tx:advice
aop:config
aop:pointcut id=”transactionPointcut”
expression=”execution(* com…*.service..*Impl.*(..))” /
aop:advisor pointcut-ref=”transactionPointcut”
advice-ref=”transactionAdvice” /
/aop:config
!– 配置druid監控spring jdbc —
bean id=”druid-stat-interceptor”
class=”com.alibaba.druid.support.spring.stat.DruidStatInterceptor”
/bean
bean id=”druid-stat-pointcut” class=”org.springframework.aop.support.JdkRegexpMethodPointcut”
scope=”prototype”
property name=”patterns”
list
valuecom…*.service.*/value
/list
/property
/bean
aop:config
aop:advisor advice-ref=”druid-stat-interceptor”
pointcut-ref=”druid-stat-pointcut” /
/aop:config
/beans
還有很多方式可以實現,這裡就簡略的描述一番。
eclipsejee怎麼連接mysql數據庫
首先你得有一個jdbc的架包
然後
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Util {
public static Connection getConnection(){
Connection con = null;
String user = “root”;//數據庫登陸用戶名
String password = “root”;//數據庫登陸密碼
String url = “jdbc:mysql://localhost:3306/password”;//數據庫庫名
String driver = “com.mysql.jdbc.Driver”;
try{
Class.forName(driver);
con = DriverManager.getConnection(url,user,password);
}catch(Exception e){
}
return con;
}
public static void main(String[] args) {
Connection con = getConnection();
String sql = “insert into stu values(null,\’hello\’)”;
PreparedStatement p = null;
try{
p = con.prepareStatement(sql);
p.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
p.close();
con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
原創文章,作者:VVQIQ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/129903.html