First post ever here :) looking franticly for help.
What I'm trying to do is to retrieve a specific image stored as blob in my database. I can't figure out why this query is not executing, I'm getting an exception as soon as I reach the executeQuery statement.
My table is:
Name xcoordinate ycoordinate vista
firstscree 0 0 imag
secondscreen 0 1 img2
... etc.
ResultSet rs = null;
Statement stmnt = null;
Connection con = null;
String host = ...
String unm = ...
String pswrd = ...
BufferedImage imgt = null;
InputStream fis = null;
int xcoord;
int ycoord;
int newcoord;
String SQLNorth = "select vista from location where xcoordinate = "+xcoord+" and ycoordinate = "+newcoord;
newcoord = ycoord + 1;
System.out.println("New coord x and y are" + xcoord + newcoord);
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmnt.executeQuery(SQLNorth);
rs.next();
fis = rs.getBinaryStream(1);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1.setImage(newImg);
My guess is that it has something to do with the way you're building the query. Try using a prepared statement instead.
ResultSet rs = null;
PreparedStatement stmnt = null;
Connection con = null;
String host = ...
String unm = ...
String pswrd = ...
BufferedImage imgt = null;
InputStream fis = null;
int xcoord;
int ycoord;
int newcoord;
String SQLNorth = "select vista from location where xcoordinate = ? and ycoordinate = ?";
newcoord = ycoord + 1;
System.out.println("New coord x and y are" + xcoord + newcoord);
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.prepareStatement(SQLNorth);
stmnt.setInt(1, xcoord);
stmnt.setInt(2, newcoord);
rs = stmnt.executeQuery(SQLNorth);
rs.next();
fis = rs.getBinaryStream(1);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1.setImage(newImg);
Related
I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.
I have a SQL Server 2008 database and I want to select data by using a String variable... here is the selection code in java:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DDS_DSN");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = 53");
while ( rs.next() ) {
String source_port = rs.getString("source_port");
System.out.println(source_port);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
I want to make it like this:
String x = "53";
try
{
.
.
rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = x");
.
.
}
could you please tell me how to do that?...
Thank you
Kind Regards
You want a parameterized query, like this:
int x = 53;
PreparedStatement ps = con.prepareStatement(
"SELECT source_port FROM request_dns " +
"WHERE destination_port = ?");
ps.setInt(1, x);
ResultSet rs = ps.executeQuery();
I don't know why but the table doesnot display. Values are being added into base table in mysql but it doesnot display in jtable.
Connection con = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = con.createStatement();
String sql = "insert into customers "+
"values("+id+", \""+name+"\", "+"\""+add+"\", "+pno+");";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery("Select * from customers;");
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
model.addColumn("CustID");
model.addColumn("CustName");
model.addColumn("CustAdd");
model.addColumn("PhoneNo");
while(rs.next()){
int tid = rs.getInt("custid");
String tname = rs.getString("custname");
String tadd = rs.getString("custadd");
long tpno = rs.getLong("phoneno");
model.addRow(new Object[]{tid, tname, tadd, tpno});
}
table.setVisible(true);
}catch(SQLException se){
jOptionPane1.showMessageDialog(this, se);
}catch(Exception e){
.
.
.
You add the JTable to the JScrollPane, but it does not look like you are adding the JScrollPane to anything. (Unless there is code that we are not seeing.)
I am trying to do something relatively simple using IdbCommand to execute an insert query.
Here's the code:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (#Date, #User, #Type, #Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "#Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "#User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "#Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "#Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
But I keep getting a MySqlException with the message "Column 'Date' cannot be null".
All my selects work fine, it's just this insert that has a problem and I can't see an obvious problem with it.
The parameter is populated with a valid DateTime during runtime.
I thought it might be related to the fact that Date is a reserved word and needs backquotes, but that's what online tutorials recommend.
Any ideas?
Found it!
For some reason instead of #, it needs ?
So the working code is:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (?Date, ?User, ?Type, ?Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "?Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "?User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "?Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "?Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
}
I using Linq DataContext.Log and I want to save sql command with parameters. how may I do this??
Now to log is writing:
SELECT [t0].[Id_User],
[t0].[FirstName], [t0].[LastName],
[t0].[UserName], [t0].[Password],
[t0].[District_Id], [t0].[Active],
[t0].[MobileDevice_Id],
[t0].[IsMobile], [t0].[IsWWW],
[t0].[IsWholesaler], [t0].[Acc_Admin],
[t0].[Warehouse_Id], [t0].[PIN],
[t0].[ValidFrom], [t0].[ValidTo],
[t0].[IsExternal], [t0].[UserType],
[t0].[DefaultDepartment_Id],
[t0].[Code], [t0].[RowsOnPage],
[t0].[ClientGroup_Id],
[t0].[ClientGroup2_Id],
[t0].[ServerHash],
[t0].[CanOrderInPacks], [t0].[Email],
[t0].[IsAdmin],
[t0].[HasAccessToAllInferiorsData],
[t0].[IsSupplier], [t0].[Position],
[t0].[syncstamp] AS [Syncstamp],
[t0].[Source], [t0].[Deleted],
[t0].[DefaultClient_Id] FROM
[dbo].[Users] AS [t0] WHERE
([t0].[UserName] = #p0) AND
([t0].[Deleted] = #p1)
I want write #p0 and #p1 to log
Param value can be read by following line of code
var results = db.calltodatabase.Where(pradicate);
IQueryable query = results;
DbCommand dbCommand = dataContext.GetCommand(query);
var result = new SqlQueryText();
result.Text = dbCommand.CommandText;
int nParams = dbCommand.Parameters.Count;
result.Params = new ParameterText[nParams];
for (int j = 0; j < nParams; j++)
{
var param = new ParameterText();
DbParameter pInfo = dbCommand.Parameters[j];
param.Name = pInfo.ParameterName;
param.SqlType = pInfo.DbType.ToString();
object paramValue = pInfo.Value;
if (paramValue == null)
{
param.Value = null;
}
else
{
param.Value = pInfo.Value.ToString();
}
result.Params[j] = param;
}