java故事_我与Java不得不说的故事

我们在第一阶段学习了如何用jdbc连接sql2k数据库。

写了一个DBConnection.java文件:

package utils;

import java.sql.*;

import java.io.*;

import java.util.*;

public class DBConnection{

public static Connection getConnection(){

Connection con=null;

String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";

String url="jdbc:sqlserver://localhost:1433;databaseName=mydb";

String username="jiangfan";

String password="123456";

try {

Class.forName(driver);

con=DriverManager.getConnection(url,username,password);

}

catch(Exception e){

e.printStackTrace();

}

return con;

}

public static Connection getConnection(String file){

Connection con=null;

try{

Properties pro=new Properties();

FileInputStream in=new FileInputStream(file);

pro.load(in);

in.close();

String driver=pro.getProperty("jdbc.driver");

String url=pro.getProperty("jdbc.url");

String username=pro.getProperty("jdbc.user");

String password=pro.getProperty("jdbc.password");

Class.forName(driver);

con=DriverManager.getConnection(url,username,password);

}

catch(Exception e){

e.printStackTrace();

}

return con;

}

}

class TestConnection{

public static void main(String[] args){

if(DBConnection.getConnection("jdbc.properties")==null)

System.out.println("连接失败!");

else

System.out.println("连接成功!");

}

}

不知道是老师讲得太飘逸了还是我理解能力太差了。对于此段代码甚为不解是什么意思。今日看了一段马士兵老师的视频,在lomboz-eclipse重写了一个数据库连接。

package com.yutian.jiangfan;

import java.sql.*;

public class jdbc {

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

Connection con=null;

Statement stmt=null;

ResultSet rs=null;

try{

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=mygame", "jiangfan", "123456");

stmt = con.createStatement();

rs   = stmt.executeQuery("select * from yanzheng");

while(rs.next()){

System.out.println(rs.getString("name"));

System.out.println(rs.getString("age"));

}

}catch(ClassNotFoundException e){

e.printStackTrace();

}catch(SQLException e){

e.printStackTrace();

}finally{

try{

if(rs !=null ){

rs.close();

rs=null;

}

if(stmt !=null){

stmt.close();

stmt=null;

}

if(con !=null){

con.close();

con=null;

}

}catch(SQLException e){

e.printStackTrace();

}

}

}

}

终于稍微弄明白连接到底是什么意思,顺便还从视频里提前学了点关于Eclipse的用法。数据库的知识非常重要,今天终于解了我们在j2se学习阶段的一个心结,一直被这些代码弄得很郁闷,今天心情好点了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值