我在我的电脑上写了一个Java程序,用jdbc连接了一个我自己电脑上的sql server数据库,如果我把这个程序发给别人,别人运行这个程序怎么能连接我这个数据库呢?
我看是不是要什么服务器,但我也不懂,有没有人教教😭
你们的电脑在同一局域网吗?在的话直接部署运行就可以。不在的话,把你的程序部署到云服务器上,或者使用内网穿透的方式让你的电脑可以被他的电脑访问。
内网穿透,可以参考这个
公网远程连接Windows SQL Server数据库【内网穿透】
同一个局域网内,localhost换成你的电脑ip
我们从控制台进行插入数据的信息的输入。(增删改都差不多)
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
Connection connection = dataSource.getConnection();
//手动输入需要插入的信息
Scanner sc = new Scanner(System.in);
System.out.println("请分别输入id、name、credit");
int id = sc.nextInt();
String name = sc.next();
int credit = sc.nextInt();
//使用?通配符来占位
String sql = "insert into subject values (?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
//具体的设置每个 ? 所占的值。
statement.setInt(1,id); //注意这里的下标也是从1开始的
statement.setString(2,name);
statement.setInt(3,credit);
System.out.println(statement);
int result = statement.executeUpdate();
System.out.println(result);
//释放资源
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
运行结果:
通过从控制台输入 id 来查询某一条数据。
//设置数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
//建立连接
Connection connection = dataSource.getConnection();
//从控制台输入需要查询subject的id
Scanner sc = new Scanner(System.in);
System.out.println("请输入需要查询的id:");
int id = sc.nextInt();
String sql = "select * from subject where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
System.out.println(statement); //查看最终的sql语句
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()){
int idSubject = resultSet.getInt(1);
String name = resultSet.getString(2);
int credit = resultSet.getInt(3);
//在控制台打印出查询的结果
System.out.println("id:"+idSubject+" name:"+name+" credit:"+credit);
}
//释放资源
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
结果:
注意:以上介绍的 JDBC 的写法是一种较为新的写法,现在也更加常见。除了这种写法外,还有一种老的写法,它是通过 反射来 设置数据源的。
使用反射的版本:
不使用的版本: