1. 程式人生 > >java通過JDBC連線資料庫及增刪改查操作

java通過JDBC連線資料庫及增刪改查操作

1.實戰資料庫資料的準備

   建立資料庫(newsmanager),然後建立表news(id,title,content,type)和newstype(id,name),其中news的type和newstype的id為主外來鍵關係,如下圖

  2.JDBC的介紹

      1)一種執行SQL語言的Java API
      2)可以對所以主流資料庫進行統一訪問(access,MySQL,sql server,Oracle)
      3)極大地減少了程式操作資料庫的複雜性
      4)jdbc使用面向物件的方式操作資料,能更好的和Java語言銜接
      5)jdbc可以直接呼叫資料庫儲存過程
      6)jdbc操作資料庫的效率很高
      7)學會了jdbc,什麼資料庫存取資料都會了
      8)但是唯一的缺點就是不安全,因為你會把資料庫的使用者名稱和密碼寫入程式碼裡,別人可以反編譯便可以獲取你的資料庫資訊,所以看你怎麼衡量吧
3.連線資料庫工具類的實現
     1)在IDE(MyEclipse/eclipse)中建立專案
           建立包com jdbc.bean(實體類包),com jdbc.dao(操作資料庫的方法),com jdbc.main(實際操作方法),com jdbc.util(工具類包)
     2)匯入MySQL連線jar包到專案中(jar包下載地址:http://dev.mysql.com/downloads/file/?id=462850)
     3)利用匯入的jar包完成連線資料庫的工具類 
           完成上述步驟的圖

          

     4)connection物件的講解和使用
            在com jdbc.util包下,建立一個類BaseConnection,它的作用是連線資料庫 ,寫上以下程式碼

package com.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class BaseConnection { 
     public static Connection getConnection(){//用這個方法獲取mysql的連線
    	 Connection conn=null;
    	 try{
    		 Class.forName("com.mysql.jdbc.Driver");//載入驅動類
    		 conn=DriverManager.   
    				 getConnection("jdbc:mysql://localhost:3306/newsmanager","root","950107");//(url資料庫的IP地址,user資料庫使用者名稱,password資料庫密碼)
    	 }catch(Exception e){
    		 e.printStackTrace();
    	 }
    	 return conn;
     }
     public static void main(String[] args){//測試資料庫是否連線成功的方法
        Connection conn=BaseConnection.getConnection();
        System.out.println(conn);
     }
     
}

     若連線成功則顯示下圖


3.查詢操作的機制和實現

   1)在com jdbc.bean包下根據資料庫的資料屬性建立News.java和Newstype.java,程式碼分別如下
         News.java程式碼

package com.jdbc.bean;

public class News {
    private int id;
    private String title;
    private String content;
    private int type;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
}

         Newstype.java程式碼

package com.jdbc.bean;

public class NewsType {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	

}

   2)在com jdbc.dao(操作資料庫的方法)下分別建立NewsDAO.java(操作news表的操作)和NewsType.java(操作newstype表的操作),程式碼如下

        NewsDAO.java

package com.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.jdbc.bean.News;
import com.jdbc.util.BaseConnection;

public class NewsDAO {
	 public ArrayList<News> getList(){//單表查詢
		   ArrayList<News> ar=new ArrayList<News>();//儲存從資料庫中取出來的資料
		   Connection conn=BaseConnection.getConnection();//獲取資料庫連線
		   //sql執行器物件
		   PreparedStatement ps=null;
		   //結果集物件
		   ResultSet rs=null;//查詢出來的資料先放到rs中
		   try{
			     String sql="select * from news";
			     ps=conn.prepareStatement(sql);
			     rs=ps.executeQuery();//執行資料庫查詢的方法,放到rs中
			     while(rs.next()){//rs物件相當於一個指標,指向資料庫的一橫行資料
			    	 News ne =new News();//封裝資料
			    	 ne.setId(rs.getInt("id"));//rs指標指向id一行獲取id一行資料,儲存到ne中
			    	 ne.setTitle(rs.getString("title"));//rs指標指向title一行獲取id一行資料,儲存到ne中
			    	 ne.setContent(rs.getString("content"));//rs指標指向content一行獲取id一行資料,儲存到ne中
			    	 ne.setType(rs.getInt("type"));//rs指標指向id一行獲取type一行資料,儲存到ne中
			    	 ar.add(ne);//通過迴圈,把資料的資料依次儲存在ne物件中,再把ne物件新增到ar陣列中方便提取
			    	 
			    	 
			     }
		   }catch(Exception e){
			   e.printStackTrace();
		   }finally{//重點下面程式碼必須寫,當資料庫使用後必須關閉,如果沒有關閉資料庫的介面有限,下次就不能連線
			   try{
				   if(rs!=null){
					   rs.close();
				   }if(ps!=null){
					   ps.close();
				   }if(conn!=null){
					   conn.close();
				   }
			   }catch(Exception e2){
				   e2.printStackTrace();
			   }
		   }
		   return ar;//返回ar
	   }
	 
	   public static void main(String[] args){
		  ArrayList<News> ar= new NewsDAO().getList();
		  for(News ne:ar){
			  System.out.println(ne.getId()+" "+ne.getTitle());
		  }
	   }
}

   如果要連結串列查詢只需把NewsDAO.java中String sql="  select  *  from news, newstype"   "where news.type =newsype.id"和ne.setName(rs.getString(”name”))再把News.java新增private String name;

出現如下圖就表示成功

  

4.新增操作的機制與實現

   只需在NewsDao.java新增方法,程式碼如下
 //該方法負責將傳遞過來的news物件中的資料存入到資料庫中
	 public void insert(News ne){
		 Connection conn=BaseConnection .getConnection();
		 PreparedStatement ps=null;
		 String sql="insert into news(title,content,type)"+
		 "values(' "+ne.getTitle()+"','"+ne.getContent()+"',"+
				 ne.getType()+")";
		 try{
			 ps= conn.prepareStatement(sql);//把寫好的sql語句傳遞到資料庫,讓資料庫知道我們要幹什麼
			 int a=ps.executeUpdate();//這個方法用於改變資料庫資料,a代表改變資料庫的條數
			 if(a>0){
				 System.out.println("新增成功");
			 }else{
				 System.out.println("新增失敗");
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }try{
			   if(ps!=null){
				   ps.close();
			   }if(conn!=null){
				   conn.close();
			   }
		   }catch(Exception e2){
				 e2.printStackTrace();
			 }
	 }

  再把public static void main(String[] args){
  News ne=new News();
  NewsDAO neda=new NewsDAO();
  ne.setTitle("成都溫江環境好");
  ne.setContent("我還是得了肺癌");
  ne.setType(2);
  neda.insert(ne);
// ArrayList<News> ar= new NewsDAO().getList();
// for(News ne:ar){
// System.out.println(ne.getId()+" "+ne.getTitle());
// }
   }
}改了

 出現如下圖就成功了

  

資料庫也更新瞭如圖


上述也可以使用佔位符,程式碼如圖


5.刪除和修改操作的機制和實現

 1)在NewsDAO.java檔案下新增deleta方法,程式碼如下
    public void delete(int id){//刪除資料庫中的資料
		 Connection conn=BaseConnection.getConnection();
		 PreparedStatement ps=null;
		 String sql="delete from news where id =?";
		 try{
			 ps=conn.prepareStatement(sql);
			 ps.setInt(1, id);
			 int a=ps.executeUpdate();
			 if(a>0){
				 System.out.println("刪除成功");
			 }else{
				 System.out.println("刪除失敗");
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 try{
				   if(ps!=null){
					   ps.close();
				   }if(conn!=null){
					   conn.close();
				   }
			   }catch(Exception e2){
				   e2.printStackTrace();
			   }
		 }
	 }

 呼叫該方法就可以刪除操作,成功如下圖


    2)在NewsDAO.java檔案下新增update方法,程式碼如下
    

//本方法用於將傳遞過來的news物件中的值,根據id主鍵,改變資料庫中的值
	 public void update(News ne){
		 Connection conn=BaseConnection.getConnection();
		 PreparedStatement ps=null;
		 String sql="update news set title=?,content=?,type=?"+
		             "where id=?";
		 try{
			 ps=conn.prepareStatement(sql);
			 ps.setString(1,ne.getTitle());
			 ps.setString(2,ne.getContent());
			 ps.setInt(3,ne.getType());
			 ps.setInt(4,ne.getId());
			 int a=ps.executeUpdate();
	      if(a>0){
				 System.out.println("修改成功");
			 }else{
				 System.out.println("修改失敗");
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 try{
				   if(ps!=null){
					   ps.close();
				   }if(conn!=null){
					   conn.close();
				   }
			   }catch(Exception e2){
				   e2.printStackTrace();
			   }
		 }
		     
	 }

  6.把這些方法串起來

在com.jdbc.main包下建立TestMain.java,程式碼如下
package com.jdbc.main;

import java.util.ArrayList;
import java.util.Scanner;

import com.jdbc.bean.News;
import com.jdbc.dao.NewsDAO;

public class TestMain {
    public static void main(String[] args){
    	
    	Scanner sc=new Scanner(System.in);
    	NewsDAO nd=new NewsDAO();
    	while(true){
    		System.out.println("1.檢視新聞 2.新增新聞 3.刪除新聞 4.退出");
    		int a=sc.nextInt();
    		if(a==1){
    			ArrayList<News> ar =nd.getListAll();
    			System.out.println("編號\t標題\t內容"); 
    			for(News ne:ar){
    				System.out.println(ne.getId()+"\t"+ne.getTitle()+"\t"+ne.getContent());
    			}
    			
    		}else if(a==2){
    			System.out.println("請輸入新聞標題內容類別編號");
    			News ne=new News();
    			ne.setTitle(sc.next());
    			ne.setContent(sc.next());
    			ne.setType(sc.nextInt());
    			boolean b=nd.insert1(ne);//呼叫插入方法
                 System.out.println(b);
    		}else if(a==3){
    			System.out.println("請輸入要刪除的新聞編號");
    			int id =sc.nextInt();
    			boolean b=nd.delete(id);//呼叫刪除方法
    			System.out.println(b);
    		}else{
    			break;
    		}
    	}
    }
}

 實現成功會出現下圖


  這就是JDBC連線任何資料庫的方法,我會把程式碼傳上來,不用積分就可以下載,希望大家多多支援我!

相關推薦

java通過JDBC連線資料庫刪改操作

1.實戰資料庫資料的準備    建立資料庫(newsmanager),然後建立表news(id,title,content,type)和newstype(id,name),其中news的type和newstype的id為主外來鍵關係,如下圖圖   2.JDBC的介紹  

Java 利用 JDBC 連線 Sqlsever2012 實現 刪改

所需驅動檔案下載 http://download.csdn.net/detail/u012320991/9378730 資料表如下: 執行結果如下: 解決過程(預設SqlSever  已安裝並配置好): 下載  JDBC 4.0 For SqlSever --->

JDBC實現資料庫刪改操作例項

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.PreparedStatement

Java通過JDBC連線資料庫的三種方式!!!並對資料庫實現刪改

前言 java連線資料庫完整流程為: 1,獲得驅動(driver),資料庫連線(url),使用者名稱(username),密碼(password)基本資訊的三種方式。 2,通過獲得的資訊完成JDBC實現連線資料庫。 注:連線前請匯入jar包,例:連線my

JDBC通過PreparedStatement 對資料庫進行刪改

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public

mongodb--java連線資料庫實現刪改

1.新建一個maven專案,匯入 <dependencies>       <dependency>         <groupId>junit</grou

Java連線資料庫DBHelper刪改[多條資料]

補充!忘記寫思路了。。。 思路 1. 使用Class.forName()載入驅動 2. 驅動管理指定資料庫並連線 Connection conn = DriverManager.getConnection() 3. 連線後,使用連接獲取預處理(處理

c#連線Access資料庫刪改

c#窗體程式對Access資料庫的增刪改查,其他資料庫可類似使用準備工作:窗體:access:版本2003(字尾.mdb,新版access可另存為2003相容版)using:using System; using System.Data; using System.Wind

通過JDBC進行簡單的刪改(以MySQL為例)

mage ron end main exce javax xtend 探索 rman 通過JDBC進行簡單的增刪改查(以MySQL為例) 目錄 前言:什麽是JDBC 一、準備工作(一):MySQL安裝配置和基礎學習 二、準備工作(二):下載數據庫對應的jar包並

通過JDBC進行簡單的刪改(以MySQL為例)(轉載)

IE trac archive solver ttl 賦值 TP 定義 for 轉載:https://www.cnblogs.com/wuyuegb2312/p/3872607.html 目錄 前言:什麽是JDBC 一、準備工作(一):MySQL安裝配置和基礎學習 二、準備

lua 連線mysql資料庫實現刪改操作(linux下示例)

(1)linux下連線資料庫: mysql -u root -p,-u 指定登入使用者,-p 指定密碼。 [[email protected]18 develop]$ mysql -u root -p Enter password: Welcome to the MySQ

JDBC操作----執行資料庫刪改 操作

      資料庫連線成功後,即可對資料庫進行具體的操作 一、執行資料庫資料的插入操作        使用PreparedStatement介面執行資料庫資料的插入操作,程式碼如下 : import java.sql.

JDBC連線MySQL的刪改

介紹:JDBC(Java DataBase Connectivity, Java資料庫連線)是一種用於執行SQL語句的Java API,可以為多種關係資料庫提供統一訪問,它由一組用 Java語言編寫的類和介面組成。 JDBC操作資料庫型別:  MySQL資料庫  準備

JavaWeb學習筆記6——JDBC連線MySql進行刪改並分頁顯示

  資料庫的增、刪、改、查是非常重要的操作,只要程式是關於資料庫的操作,無論程式大小,歸根結底都是這4種操作的使用。 連線MySql資料庫的過程: 1、註冊驅動 DriverManager.registerDriver(new com.mysql.jdbc.Driver()

JavaWeb學習筆記6——JDBC連線MySql進行刪改

資料庫的增、刪、改、查是非常重要的操作,只要程式是關於資料庫的操作,無論程式大小,歸根結底都是這4種操作的使用。 連線MySql資料庫的過程: 1、註冊驅動 DriverManager.registerDriver(new com.mysql.jdbc.Driver

flask連線資料庫刪改

flask日常步驟省略 增 1 #建立資料庫物件 2 db = SQLAlchemy(app) 3 4 #建立資料庫類,用來對映資料庫表,將資料庫的模型作為引數傳入 5 class User(db.Model): 6 #宣告表名 7 __tablename__ = '

類封裝版學生管理系統,連線資料庫刪改,拿去用,不謝。

# coding = utf-8 import sqlite3 class Student(object): def __init__(self, id, name, age, sex, phone): self.id = id self.name

Java實現控制檯對資料庫刪改(Eclipse)

package com.hznu.qjc.daos; import com.hznu.qjc.users.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; impor

二叉樹時間複雜度分析刪改操作java實現

順序表和連結串列的時間複雜度由給定條件不同從而會得出不同的時間複雜度結果,對於程式設計時並不總是最好用的儲存方式。二叉樹是一種更加穩定的資料儲存方式,其複雜度總是能表示為一個固定的形式。以下來分析二叉樹增刪改查操作做的時間複雜度。 設有如下資料需要進行二叉樹形式儲存:

C# 連線資料庫實現刪改

class Program { private static string urls = "server=127.0.0.1;port=3306;user=root;password=123; database=abc;"; private MySqlConne