本文主要是介绍jdbc连接myslq和sql两种数据库代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用jdbc连接mysql数据库
package com.nicolashe.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class DbUtil {private String dbUrl="jdbc:mysql://localhost:3306/db_book";private String dbUserName="root";private String dbPassword="root";private String jdbcName="com.mysql.jdbc.Driver";public Connection getCon() throws Exception{Class.forName(jdbcName);Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);return con;}public void closeCon(Connection con) throws Exception{if(con!=null){con.close();}}public static void main(String[] args ){DbUtil dbUtil=new DbUtil();try {dbUtil.getCon();System.out.println("数据库连接成功");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
连接微软的sql数据库:
package com.nicolashe.util;
import java.sql.*;public class Main { private String url="jdbc:sqlserver://localhost:1433;databaseName=test"; private String userName="hyx"; private String password="hyx"; private Connection con; public Main(){ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con=DriverManager.getConnection(url,userName,password); } catch (ClassNotFoundException ex) { System.out.println("Error:Can't Load the SQL Server Driver"); //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); }catch(SQLException ex){ System.out.println("Error:Can't connect to Database!"); // Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { Main main=new Main(); String sql="select * from users"; if(main.con==null) return; try{ Statement st=main.con.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)); } }catch(SQLException e){ e.printStackTrace(); } } }
这篇关于jdbc连接myslq和sql两种数据库代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!