测试jdbc连接mysql_jdbc连接数据库-怎样测试java连接数据库是否成功??????? 爱问知识人...

java连接sql server的两种不同方式:

1 使用JDBC直接连接

import java。sql。*;

public class JdbcSqlserver {

public static void main(String[] agrs) throws Exception {

Connection conn = null;

ResultSet rs = null;

Statement stmt = null;

String connURL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_test_com;User=sa;Password=5510803";//note the username and password

String sqldriver = "com。

microsoft。jdbc。sqlserver。SQLServerDriver";

try{

rName(sqldriver);//注册/加载驱动程序

}

catch(Exception e)

{

intln("can not load Jdbc for sqlserver driver");

intln( String());

}

conn = tConnection(connURL);

stmt = eateStatement();

rs = stmt。

executeQuery("SELECT * FROM test"); //执行查询,得到以行为单位的数据集

while ( xt()) { //遍历每行

/*

int( tString(1));

int("\t" + tString(2));

intln("\t\t" + tString(3));

*/

int( tString("ID") + "\t");

int( tString("Name") + "\t");

intln( tString("Age"));

}

ose();

ose();

ose();

}

}

2 使用JDBC-ODBC连接

/*

应用JDBC-ODBC桥

1。

在sqlserver中建数据库和表

2。 创建数据源]

(1) 开始->设置->控制面板->管理工具->ODBC数据源

(2) 在USER DSN下点击Add按钮,弹出Create NewDataSource对话框

(3) 选择sqlserver->完成

(4) 指定Name为你的数据源名,server为sqlserver服务器所在的主机的IP地址,若在本机,可以为(local),localhost, 等。

(5) 选择With……………by user,设置用户名和密码

(6) 选择Change the default database to:

在下拉列表中选择合适的数据库,也就是说要查询或更新的表所在的数据库的名字,如db_test_com 表中有个 test表,那么就设置成db_test_com

(7) Test DataSource(测试数据源),不成功返回第三步重新配置。

*/

import java。sql。*; //导入SQL包

public class JdbcOdbcSqlserver {

public static void main(String[] args) throws Exception {

rName("sun。

jdbc。odbc。JdbcOdbcDriver"); //加载驱动程序

Connection con = tConnection("jdbc:odbc:sqlserver_test"); //取得数据源并进行连接

Statement st = eateStatement(); //创建语句

ResultSet rs = st。

executeQuery("SELECT * FROM test"); //执行查询,得到以行为单位的数据集

while ( xt()) { //遍历每行

int( tString("ID") + "\t");

int( tString("Name") + "\t");

intln( tString("Age"));

}

ose();

ose();

ose();

}

}。

全部

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值