VisualStudioでJavaプロジェクトを作成してローカルで起動しているMicrosoftSQLServerに接続したいです。
接続するクラスのコードは下記です。
このコードを実行すると下記のエラーが発生します。解決方法を知りたいです。
JDBCのパスはC:\jar\sqljdbc_11.2\jpn\mssql-jdbc-11.2.0.jre18.jarで、Windowsの設定で
CLASSPATH=C:\jar\sqljdbc_11.2\jpn\mssql-jdbc-11.2.0.jre18.jarを設定しています。
調べるとプロジェクト配下のlibフォルダにjdbcの.jarファイルを置いている記事を見つけましたがlib配下に配置するとエラー: メイン・クラスSQLDatabaseConnectionを検出およびロードできませんでした
原因: java.lang.ClassNotFoundException: SQLDatabaseConnectionというエラーがでてしまいます。
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost.database.windows.net:1433;Database=sandbox_cd;integratedSecurity=false;user=sa;password=Password123
SQLDatabaseConnection
1import java.sql.Connection; 2import java.sql.DriverManager; 3import java.sql.PreparedStatement; 4import java.sql.ResultSet; 5import java.sql.Statement; 6 7public class SQLDatabaseConnection { 8 9 // Connect to your database. 10 // Replace server name, username, and password with your credentials 11 static final String URL = "jdbc:sqlserver://localhost.database.windows.net:1433;" 12 + "Database=sandbox_cd;integratedSecurity=false;" 13 + "user=sa;password=Password123"; 14 public static void main(String[] args) { 15 16 String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES " 17 + "('NewBike', 'BikeNew', 'Blue', 50, 120, '2016-01-01');"; 18 19 ResultSet resultSet = null; 20 21 try ( 22 Connection connection = DriverManager.getConnection(URL); 23 PreparedStatement prepsInsertProduct = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); 24 ) { 25 26 prepsInsertProduct.execute(); 27 // Retrieve the generated key from the insert. 28 resultSet = prepsInsertProduct.getGeneratedKeys(); 29 30 // Print the ID of the inserted row. 31 while (resultSet.next()) { 32 System.out.println("Generated: " + resultSet.getString(1)); 33 } 34 } 35 // Handle any errors that may have occurred. 36 catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40}
あなたの回答
tips
プレビュー