學習總結------用JDBC串連MySQL

來源:互聯網
上載者:User

標籤:web   code   連結   資料庫   技術分享   標記   div   ges   html 4.01   

1.下載MySQL的JDBC驅動

地址:https://dev.mysql.com/downloads/connector/

 

為了方便,直接就選擇合適自己的壓縮包

 

 

跳過登入,選擇直接下載

下載完成後,解壓  mysql-connector-java-5.1.42-bin.jar  ,複製

 

 在解壓的檔案中,找到

 

 

 粘貼到WebContent—WEB-INF—lib

在ecplise中選擇lib檔案夾,直接Ctrl+V粘貼即可

 

 

 

2.建立一個.jsp頁面

代碼:

<%@page import="java.text.SimpleDateFormat"%><%@page import="java.sql.Date"%><%@page import="java.sql.PreparedStatement"%><%@page import="java.sql.DriverManager"%><%@page import="java.sql.Connection"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><%Date date = new Date(new java.util.Date().getTime());out.println("時間:"+date);//聲明 name,timeString name = "小明";//擷取目前時間//載入驅動Class.forName("org.gjt.mm.mysql.Driver");out.println("載入驅動成功"); //資料庫路徑儲存到 url變數String url="jdbc:mysql://127.0.0.1:3306/test1?user=root&password=123456"; //要執行的語句儲存到sql變數     //儲存添加欄位語句String sql1="ALTER TABLE tt2 ADD birt date";    //儲存添加資訊語句String sql = "insert into tt2(name,birt) values(?,?)";  //連結資料庫Connection conn = DriverManager.getConnection(url);//要準備執行的語句    //給tt2表添加欄位birtPreparedStatement ps1 = conn.prepareStatement(sql1);    //輸入資訊name ,birtPreparedStatement ps2 = conn.prepareStatement(sql);    //找到第1個?號標記,給予name的值ps2.setString(1,name);    //找到第2個?號標記,給予time的值ps2.setDate(2,date);//執行ps1.execute();ps2.execute();//關閉連結    //JDBC介面的斷開ps1.close();    ps2.close();    //資料庫斷開conn.close();        out.print("資料添加完畢");%></body></html>

 

3.部分代碼解釋3.1  理解圖:

 

 3.2  用JDBC串連的MySQL的路徑(url)

 

 

 3.3  Connection對象

 

 3.4  PreparedStatement對象

 

 3.5  execute()方法

執行

 

 

 3.6  close()方法

 

學習總結------用JDBC串連MySQL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.