java连接mysql数据库 java连接sql server数据库

前端之家收集整理的这篇文章主要介绍了java连接mysql数据库 java连接sql server数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在java的应用中,我们经常会对数据库进行必要的操作,下来我们就了解一下如何用java连接MysqL数据库 以及java连接sql server数据库

一、MysqL

<div class="jb51code">
<pre class="brush:java;">
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestOne {

private static Connection connection;
private static Statement statement;
private static ResultSet result;

public static void main(String[] args) {
try {
//加载jdbc驱动程序
Class.forName("com.mysql.jdbc.Driver");
//指明主机名(默认为:127.0.0.1)和端口号(默认为:3306)以及数据库名(必须指定)
String url = "jdbc:mysql://localhost:3306/test1";
//与数据库建立连接
connection = DriverManager.getConnection(url,"root","123456");
//创建一个Statement对象将SQL语句发送到数据库
statement = connection.createStatement();
//将查询结果返回给result
result = statement.executeQuery("select *from user");
while(result.next()){
System.out.println("name:" + result.getString(1) + " password:" + result.getString(2));
}
connection.close();
result.close();
statement.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(connection != null)
connection.close();
if(result != null)
result.close();
if(statement != null)
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**

  • mysql> select from user;
    +----------+----------+
    | name | password |
    +----------+----------+
    | lisi | 123456 |
    | wangwu | 123456 |
    | zhangsan | 123456 |
    +----------+----------+
    *3 rows in set (0.54 sec)
  • 在java中的输出结果
    name:lisi password:123456
    name:wangwu password:123456
    name:zhangsan password:123456
    */

二、sql server

sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.sqlException; import java.sql.Statement;

public class TestDemo {

public static void main(String[] args) {
String url="jdbc:sqlserver://localhost:1433;DatabaseName=Contellation";
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.sqlServerDriver");
conn = DriverManager.getConnection(url,"sa","");
Statement statement=conn.createStatement();
ResultSet rs = statement.executeQuery("select * from dbo.登陆表 ");
while(rs.next()){
System.out.println("用户名:" + rs.getString(1) + " 密码:" + rs.getString(2));
}
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (sqlException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

猜你在找的Java相关文章