欢迎来到天天文库
浏览记录
ID:44870955
大小:76.50 KB
页数:3页
时间:2019-10-31
《JDBC连接SQLServer和MySQL基础程序源码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、连接SQLServerpackagejdbc.sqlserver.test;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;publicclassstudent_test{publicstaticvoidmain(String[]args){//创建空连接Connectionconn=null;//加载数据库驱动try{Class.forName("com
2、.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(ClassNotFoundExceptione){e.printStackTrace();}//建立数据库连接try{conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=MYDB","sa","123456");}catch(SQLExceptione){e.printStackTrace();}//创建语句Stringsql="select*fromstudent
3、";//执行语句try{Statementstmt=conn.createStatement();ResultSetrs=stmt.executeQuery(sql);//遍历结果集while(rs.next()){intid=rs.getInt("id");Stringname=rs.getString("name");Stringemail=rs.getString("email");System.out.println(id+"t"+name+"t"+email);}}catch(SQLExceptione){e.printStackTrace();}//关闭
4、数据库连接finally{if(conn!=null){try{conn.close();}catch(SQLExceptione){e.printStackTrace();}}}}}连接MYSQLpackagejdbc.mysql.test;importjava.sql.*;publicclassStudentTest{publicstaticvoidmain(String[]args){Connectionconn=null;try{Class.forName("com.mysql.jdbc.Driver");}catch(ClassNotFoundExceptio
5、ne){e.printStackTrace();}try{conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/MYDB","root","123456");}catch(SQLExceptione){e.printStackTrace();}Stringsql="select*fromstudent";try{Statementstmt=conn.createStatement();ResultSetrs=stmt.executeQuery(sql);while(rs.next()){intid=r
6、s.getInt("id");Stringname=rs.getString("name");Stringemail=rs.getString("email");System.out.println(id+"t"+name+"t"+email);}}catch(SQLExceptione){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(SQLExceptione){e.printStackTrace();}}}}}
此文档下载收益归作者所有