首页 / JAVA / java连接数据库步骤
java连接数据库步骤
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java连接数据库步骤,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2793字,纯文字阅读大概需要4分钟。
内容图文
Connection : 连接数据库并担任传送数据的任务 * Statement : 执行SQL语句 * ResultSet :保存Statement执行后产生的查询结果 1.注册驱动 Class.forName(JDBC驱动类); 2.获取数据库连接 Connection con=DriverManager.getConnection(JDBC url,数据库用户名,密码); 3.获得 Statement对象 Statement stmt=con.createStatement(); 4.执行SQL语句 ResultSet rs=stmt.executeQuery(select a,b from table); 5.处理执行结果 while(rs.next()){ int x=rs.getInt("a"); String s=rs.getString("b"); *数据类型要相匹配 } 6.释放资源 1.rs.close(); 2.stmt.close(); 3.con.close(); *顺序倒过来依次关闭 实例: Java使用PreparedStatement接口插入数据库信息 public class PreparedStatementDemo01 { public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; public static final String DBURL = "jdbc:mysql://localhost:3306/"; public static final String DBUSER = "root"; public static final String DBPASS = "root"; public static void main(String args[]) throws ParseException, ClassNotFoundException, SQLException { Connection conn = null; //数据库连接 PreparedStatement pstmt = null; //数据库操作 Statement stmt = null; ResultSet rs = null; //Rs接口 String name = "黄鹏"; String password = "1598741"; int age = 21; String sex = "男"; String birthday ="1992-04-30"; Date temp = null; temp = new SimpleDateFormat("yyyy-MM-dd").parse(birthday); java.sql.Date bri = new java.sql.Date(temp.getTime()); //创建数据库操作语句 String sql1 = "CREATE DATABASE MyDemo;"; //选择使用哪个数据库的语句 String sql2 = "USE MyDemo;"; //创建数据库表操作语句 String sql3 = "CREATE TABLE user(name varchar(20) primary key,password varchar(20),age int,sex varchar(10),birthday Date);"; //查询数据库语句 String sql5 = "select * from user;"; //用PreparedStatement执行的插入语句 String sql4 = "INSERT INTO user(name,password,age,sex,birthday) VALUES(?,?,?,?,?);"; //加载驱动程序 Class.forName(DBDRIVER); //连接mysql数据库 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //实例化PreparedStatement pstmt = conn.prepareStatement(sql4); //设置第一个?内容 pstmt.setString(1, name); //设置第二个?内容 pstmt.setString(2, password); //设置第三个?内容 pstmt.setInt(3, age); //设置第四个?内容 pstmt.setString(4,sex); //设置第五个?内容 pstmt.setDate(5, bri); //执行数据库更新,不需要sql stmt = conn.createStatement(); stmt.execute(sql1); stmt.execute(sql2); stmt.execute(sql3); pstmt.executeUpdate(); rs = stmt.executeQuery(sql5); //向控制台输出信息 while(rs.next()) { String QueryName = rs.getString("name"); String QueryPwd = rs.getString("password"); int QueryAge = rs.getInt("age"); String QuerySex = rs.getString("sex"); Date QueryDate = rs.getDate("birthday"); System.out.println("name:"+QueryName+" pwd:"+QueryPwd+" "+QueryAge+" sex:"+QueryPwd+" date:"+QueryDate); } pstmt.close(); conn.close(); } }
java连接数据库步骤
标签:
本文系统来源:http://www.cnblogs.com/wlx520/p/4501847.html
内容总结
以上是互联网集市为您收集整理的java连接数据库步骤全部内容,希望文章能够帮你解决java连接数据库步骤所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。