Informix IfmxStatement.getSerial() to PostgreSQL substitute - database

Could you help me, because I have a problem? My task is to port a database from Informix to PostgreSQL, but someone use IfmxStatement method getSerial(), and I can't find any substitute for it in PostgreSQL.
Integer serial = new Integer(((IfmxStatement) stmt.getSerial());

You can use getGeneratedKeys() which is part of JDBC
stmt.executeUpdate("INSERT INTO ...", Statement.RETURN_GENERATED_KEYS);
// retrieve the auto generated key/keys
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
int serial = rs.getInt(1);
}

Thank you, this is my solution.
int serial=0;
ResultSet rs = null;
String query="SELECT nextval('id_seq');";
try
{
rs=stmt.executeQuery(query);
if (rs.next())
{
serial = rs.getInt(1);
}
setId(serial);

Related

SQLNCLI11 provider has the error of The fractional part of the provided time value overflows

I have the following connection string:
provider=SQLNCLI11;Server=[server];Database=[db];uid=[uid];pwd=[pwd]
and I have the following code:
OleDbCommand oComm = new OleDbCommand();
oComm.Connection = OleConnection;
oComm.Transaction = m_oleTran;
oComm.CommandText = sSQL;
oComm.CommandTimeout = TimeOut;
BuildParams(ref oComm, sCols, (object [])oVals);
if (oComm.Connection.State == ConnectionState.Closed)
oComm.Connection.Open();
m_RowsAffected = oComm.ExecuteNonQuery();
if (m_oleTran == null)
oComm.Connection.Close();
oComm.Dispose();
private void BuildParams(ref OleDbCommand oComm, string [] sCols, object [] oVals)
{
for (int i = 0; i< sCols.Length; i++)
{
if (sCols.Length > 0)
oComm.Parameters.AddWithValue(sCols[i], oVals[i]);
}
}
when I executed a simple update SQL statement, I got the following error
The fractional part of the provided time value overflows the scale of the corresponding SQL Server parameter or column. Increase bScale in DBPARAMBINDINFO or column scale to correct this error. at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
Any ideas?
Thanks,
Solution used in DTSX Script Task with VB language.
For compliance reasons our customer asked us to change the SQL Server provider in a database version upgrade. And we started getting the same error when trying to save the dates. The date sent to the database was not on the correct scale. We could have changed the data type in the database, but we chose not to do so after we tested this very simple solution that worked. We just use a
.ToString("yyyy-MM-dd HH:mm:ss")
and send a string instead of a date with the correct size and it went through the provider and the database and saved without problems.
Provider=SQLNCLI11;
SOLUTION:
com.Parameters.AddWithValue("#COD_INTERFACE", SqlDbType.Int)
com.Parameters.AddWithValue("#COD_SEQUENCIAL", SqlDbType.Int)
com.Parameters.AddWithValue("#DTA_GERACAO", SqlDbType.DateTime)
com.Parameters.AddWithValue("#DTA_IMPORTACAO", SqlDbType.DateTime)
com.Parameters("#COD_INTERFACE").Value = CInt(Dts.Variables("User::intCodigoInterface").Value)
com.Parameters("#COD_SEQUENCIAL").Value = CInt(Dts.Variables("User::intSequencialArquivo").Value)
com.Parameters("#DTA_GERACAO").Value = CDate(Dts.Variables("User::dtaGeracaoArquivo").Value).ToString("yyyy-MM-dd HH:mm:ss")
com.Parameters("#DTA_IMPORTACAO").Value = Now.ToString("yyyy-MM-dd HH:mm:ss")

Java PreparedStatement:com.microsoft.sqlserver.jdbc.SQLServerException:parameter index out of range

I'm try to execute a SQL query using java PreparedStatement in JAVA 8 and code blow
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(URl,user,"");
String sql = "Select Grade from XS_KC where Snum=? and Cnum=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "020101");
pst.setString(2, "102");
rs = pst.executeQuery();
while(rs.next())
{
System.out.print(rs.getString(1));
}
I get the fllowing error:com.microsoft.sqlserver.jdbc.SQLServerException:parameter index out of range
But if i use
stat = con.createStatement();
rs = stat.executeQuery("Select Grade from XS_KC where Snum='020101' and Cnum='101'");
I can get the result
What's wrong??
The first ? in your query is Unicode 0x1FFF rather than 0x3F00 (question mark). Try:
String sql = "Select Grade from XS_KC where Snum=? and Cnum=?";

Java & SQL Server exception: The statement did not return a result set

I'm creating an insurance management system for my DBMS project in university, and I am having a problem with deleting a record from SQL Server. It throws an exception:
SqlException: com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
It also successfully deleted a record from my database. Could anyone please tell me how to remove this kind of exception?
String SQL="delete from INMS_3 where Agent_Id=? and First_Name=? and Last_Name=? and User_Name=? and Phone_no=?";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=INMS;user=TestingUser;password=1234;";
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected to sql server");
String str=jTextField1.getText();
String str1=jTextField2.getText();
String str2=jTextField3.getText();
String str3=jTextField4.getText();
String str4=jTextField5.getText();
PreparedStatement st = con.prepareStatement(SQL);
st.setString(1, str);
st.setString(2,str1);
st.setString(3,str2);
st.setString(4,str3);
st.setString(5, str4);
ResultSet rs = st.executeQuery();
if(rs.next());
{
JOptionPane.showMessageDialog(null,"Deleted Succesfully");
}
if(!rs.next())
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
else
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
I think you are using the wrong thing to perform the delete operation.
Try using st.executeUpdate() instead of ResultSet rs = st.executeQuery() - you are executing a delete rather than something that would return a result set.
This is not a problem with SQL Server. The problem is with your code (what is that? C#? The object is set to expect a result set from the server, but the query is a DELETE statement, and those return no rows... ever.
State the programing language, and research for how to execute statement instead requesting result sets.
This line makes sense for a SELECT not for an UPDATE
ResultSet rs = st.executeQuery();
if you're executing a delete statement, why are you executing
ResultSet rs = st.executeQuery();
Here's a sample c# ado.net. concept it the same if you're using java.
using(var conn = new SqlConnection("my connection string"))
{
var deleteCmd = new SqlCommand();
deleteCmd.Connection = conn;
deleteCmd.CommandType = CommandType.Text;
deleteCmd.CommandText = #"
DELETE Accounts
WHERE account_id = #p_account_id
";
deleteCmd.Parameters.AddWithValue("p_account_id", 123);
conn.Open();
deleteCmd.ExecuteNonQuery();
}

Maximum length of string which can be returned from stored proc in SQL Server 2008 to .net apps

I am returning a static string from a stored procedure (in SQL Server 2008) as below:
select 'abcdefgh.........xyz'
If the static string length is exceeding more than some limit (eg:8kb) then only partial string (eg:7kb) is returned to the .net apps.
Though I tried in different ways like assigning static string to varchar(max) and selecting the variable, is still returning only partial string.
I should return complete string which could be of max of 5mb. So, main concerns:
What is the max string length I can return from a stored procedure
How to return 5 mb string from stored procedure to .net apps.
I request someone can help me to resolve this issue.
please find the code below
using (SqlCommand command = new SqlCommand(Source.GetExportRecordSP, Connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#CandidateRecordID ", SqlDbType.NVarChar, 32)).Value = record;
try
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
using (SqlDataReader reader = command.ExecuteReader())
{
if(reader.Read())
{
xmlRecord = new XmlDocument();
xmlRecord.LoadXml(reader.GetString(0));
}
}
}
catch (Exception Ex)
{
Logging.WriteError(string.Format("Error while retrieving the Record \"{0}\" details from Database. Exception: {1} ", Ex.ToString()));
throw;
}
}
Thanks in advance geeks.
Since you appear not to be using an OLEDB connection (which has an 8k limit), I think the problem is in your procedure code.
Or, perhaps, the compatibility version of your database is set to something other than SQL Server 2008 (SQL Server 2000 could not return more than 8k using GetString()).
Thanks for support, I found 1 fix for this at
http://www.sqlservercentral.com/Forums/Topic350590-145-1.aspx
Fix is, declare a variable, and should be initlized to empty string and concatenated with the main string.
DECLARE #test varchar(MAX);
set #test =''
select #test = #test + '<Invoice>.....'
If the string length is <8000 it will work without the above approach.
Thanks all.

JDBC - prepareStatement - How should I use it?

I saw this example somewhere:
rs = connection.prepareStatement("select * from table").executeQuery();
Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?
The way in which I usual I use prepareStatement object is something like this:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
Later Edit:
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced
Here's a partial example how to use this interface:
static final String USER = "root";
static final String PASS = "newpass";
Connection conn = DriverManager.getConnection(myUrl, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, 808027);
preparedStmt.setString(2, "Davis");
preparedStmt.setString(3, "Felicita");
preparedStmt.setDate(4, startDate);
preparedStmt.setString(5, "Venice");
// execute the preparedstatement
preparedStmt.execute();
conn.close();
You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.
Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.
of course u can use a string variable for the query in which u put in ur dynamic data and run it.
rs = connection.prepareStatement(variable).executeQuery();
The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = getConn();
ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append()'s or +'s, to helps prevent sql injection
ps.setLong(1, 12l);
rs = ps.executeQuery();
while (rs.next()) {
... act ...
}
} catch ( Exception e) {
} finally {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
}
Who said java was verbose. :)

Resources