码迷,mamicode.com
首页 > 数据库 > 详细

java数据库学习

时间:2019-04-30 19:56:24      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:nic   添加   todo   exe   成功   inf   coding   .exe   int   

//编写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数据库学习

标签:nic   添加   todo   exe   成功   inf   coding   .exe   int   

原文地址:https://www.cnblogs.com/gdxhr/p/10797668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!