1. 程式人生 > >java數據庫學習

java數據庫學習

stat 類名 true .sql pri exce [] ner mysql

//編寫db類
/* a加載驅動 驅動類要全路徑 包名+類名 suround with try/catch
* b設置參數url user pwd
* c.連接數據庫(import ‘Connection‘ com.mysql.jdbc) 驅動管理器(DriverManager).獲得鏈接(getConnection)利用提示輸入帶(url,userName,passW)
* 鏈接不成功 檢查驅動類全路徑是否寫對 2(添加強制轉換) add cast to Connection 3(添加catch子句) add catch clause to surrounding try
* d.編寫sql語句

* String sql="";
* insert into studentinfo values(?,?,?,?)
* e.編譯sql語句
* 1準備陳述PreparedStatement pre = (PreparedStatement) conn.prepareStatement(sql);
* 2{SQL語句中有?代替值時用 pre.setString(1,"1616012308")選用};
* pre.executeUpdate();//executeUpdate返回的是int型,表明受影響的行數,通常是執行了insert、update、delete等操作。
* executeQuery()
*/

準備工具

jdbc包

鏈接:https://pan.baidu.com/s/1xCi3aV3oa50BK7tmDSGRaA
提取碼:f85s
mysql管理工具

鏈接:https://pan.baidu.com/s/1eEZSFApO7iViAj2WddhG9A
提取碼:b5im

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class Dateconnection {

	public static void main(String[] args) {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/javalearner?useUnicode=true&characterEncoding=utf8";
			String user="root";
			String passWord="root";
			Connection conn=(Connection) DriverManager.getConnection(url, user, passWord);
			System.out.println(conn);
			
			//插入
			String sql_insert="insert into studentinfo values(?,?,?,?)";
			PreparedStatement  pre = (PreparedStatement) conn.prepareStatement(sql_insert);
			pre.setString(1,"1616012370");
			pre.setString(2,"小張");
			pre.setInt(3,1);
			pre.setInt(4, 21);
			pre.executeUpdate();
			//查詢
			String sql_s="select * from studentinfo";
			PreparedStatement  pre_s = (PreparedStatement) conn.prepareStatement(sql_s);
			ResultSet rs = pre_s.executeQuery();
			while(rs.next()){
				String num = rs.getString("studentNum");
				String name = rs.getString("name");
				int sex = rs.getInt("sex");
				int age = rs.getInt("age");
				
				System.out.println(num+","+name+","+sex+","+age);
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

  

java數據庫學習