
public class MSSQLText
{
public static void main(String args[])
{
String url="jdbc:microsoft:sqlserver://localhost:1433DatabaseName=Northwind"
String user="sa"//这里替换成你自已的数据库用户名
String password="sa"//这里替换成你自已的数据库用户密码
String sqlStr="select CustomerID, CompanyName, ContactName from Customers"
try
{ //这里的异常处理语句是必需的.否则不能通过编译!
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver")
System.out.println("类实例化成功!")
Connection con = DriverManager.getConnection(url,user,password)
System.out.println("创建连接对像成功!")
Statement st = con.createStatement()
System.out.println("创建Statement成功!")
ResultSet rs = st.executeQuery(sqlStr)
System.out.println(" *** 作数据表成功!")
System.out.println("----------------!")
while(rs.next())
{
System.out.print(rs.getString("CustomerID") + "")
System.out.print(rs.getString("CompanyName") + "")
System.out.println(rs.getString("ContactName"))
}
rs.close()
st.close()
con.close()
}
catch(Exception err){
err.printStackTrace(System.out)
}
}
}
使用java的jdbc来连接数据库如连接mysql(其余数据库类似),引入mysql-connector-java-5.1.24.jar包到工程中,在程序中可以这样连接mysql:
String Server = 你服务器的ip
String User = 你的账号名
String Password = 你的密码
String Database = 你的数据库名
// 驱动程序名
String driver = "com.mysql.jdbc.Driver"
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://"+Server+"/" + Database
// 加载驱动程序
Class.forName(driver)
// 连续数据库
Connection conn = DriverManager.getConnection(url, User, Password)
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!")
// statement用来执行SQL语句
Statement statement = conn.createStatement()
String sql = "select ** from ** where **"
ResultSet rs = statement.executeQuery(sql)
//假设数据库表只有两个属性值,一个属性值为String类型,另一个为Int类型
while(rs.next()) {
System.out.println(rs.getString(1)+" " +rs.getInt(2) )
}
public class ParameterizedQuery {public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
InputStreamReader isr=new InputStreamReader(System.in)
BufferedReader br=new BufferedReader(isr)
//提示用户输入用户名和密码
System.out.println("请输入用户名:")
String name=br.readLine()
System.out.println("请输入密码:")
String pwd=br.readLine()
//建立数据库链接
String driver="com.mtsql.jdbc.Driver"
//访问数据库
String url="jdbc:mysql://127.0.0.1:3306/users"
String user="root"
String password="root"
//加载驱动
Class.forName(driver)
//连续数据库
Connection conn=DriverManager.getConnection(url,user,password)
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Datebase")
//statement用来执行SQL语句
Statement statement=conn.createStatement()
String sql="select count(*) from users where name='"+name+"'and password='"+pwd+"'"
//将name的数据赋值给查询语句中name
//将pwd的数据赋值给查询语句中password
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)